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,178
10.02.2019 12:44:46
-3,600
a7e393a2f33f1963dd5d8fa14418c21476492875
Multiple changes for code flagged by pylint 2.1.1
[ { "change_type": "MODIFY", "old_path": ".pylintrc", "new_path": ".pylintrc", "diff": "@@ -105,6 +105,10 @@ evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / stateme\n# evaluation report (RP0004).\n#comment=no\n+# Activate the evaluation score.\n+# score=yes\n+score=no\n+\n[VARIABLES]\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -372,7 +372,7 @@ class ViewListResource(ResourceMixin, Resource):\n# Default to user supplied data\nview_name = form.name.data\nquery_string = form.query.data\n- query_filter = json.dumps(form.filter.data, ensure_ascii=False),\n+ query_filter = json.dumps(form.filter.data, ensure_ascii=False)\nquery_dsl = json.dumps(form.dsl.data, ensure_ascii=False)\nif isinstance(query_filter, tuple):\n@@ -391,7 +391,7 @@ class ViewListResource(ResourceMixin, Resource):\n# Copy values from the template\nview_name = searchtemplate.name\nquery_string = searchtemplate.query_string\n- query_filter = searchtemplate.query_filter,\n+ query_filter = searchtemplate.query_filter\nquery_dsl = searchtemplate.query_dsl\n# WTF form returns a tuple for the filter. This is not\n# compatible with SQLAlchemy.\n@@ -1088,11 +1088,10 @@ class UploadFileResource(ResourceMixin, Resource):\nif timeline:\nreturn self.to_json(\ntimeline, status_code=HTTP_STATUS_CODE_CREATED)\n- else:\n+\nreturn self.to_json(\nsearchindex, status_code=HTTP_STATUS_CODE_CREATED)\n- else:\nraise ApiHTTPError(\nmessage=form.errors['file'][0],\nstatus_code=HTTP_STATUS_CODE_BAD_REQUEST)\n@@ -1286,6 +1285,8 @@ class CountEventsResource(ResourceMixin, Resource):\nclass TimelineCreateResource(ResourceMixin, Resource):\n+ \"\"\"Resource to create a timeline.\"\"\"\n+\n@login_required\ndef post(self):\n\"\"\"Handles POST request to the resource.\n@@ -1343,11 +1344,10 @@ class TimelineCreateResource(ResourceMixin, Resource):\nif timeline:\nreturn self.to_json(\ntimeline, status_code=HTTP_STATUS_CODE_CREATED)\n- else:\n+\nreturn self.to_json(\nsearchindex, status_code=HTTP_STATUS_CODE_CREATED)\n- else:\nraise ApiHTTPError(\nmessage=\"failed to create timeline\",\nstatus_code=HTTP_STATUS_CODE_BAD_REQUEST)\n@@ -1478,7 +1478,8 @@ class GraphResource(ResourceMixin, Resource):\nsketch_id: Integer primary key for a sketch database model\nReturns:\n- Graph in JSON (instance of flask.wrappers.Response)\n+ Graph in JSON (instance of flask.wrappers.Response) or None if\n+ form does not validate on submit.\n\"\"\"\n# Check access to the sketch\nSketch.query.get_with_acl(sketch_id)\n@@ -1517,6 +1518,8 @@ class GraphResource(ResourceMixin, Resource):\n}\nreturn jsonify(schema)\n+ return None\n+\nclass GraphViewListResource(ResourceMixin, Resource):\n\"\"\"Resource to get result from graph query.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_timeframe.py", "new_path": "timesketch/lib/analyzers/browser_timeframe.py", "diff": "@@ -78,7 +78,7 @@ def fix_gap_in_list(hour_list):\nif len(runs) <= 2:\nreturn hours\n- elif len_runs < len(runs):\n+ if len_runs < len(runs):\nreturn fix_gap_in_list(hours)\n# Now we need to remove runs, we only need the first and last.\n@@ -143,7 +143,7 @@ def get_active_hours(frame):\nif number_runs == 1:\nreturn hours, threshold, frame_count\n- elif number_runs == 2 and runs[0][0] == 0:\n+ if number_runs == 2 and runs[0][0] == 0:\n# Two runs, first one starts at hour zero.\nreturn hours, threshold, frame_count\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/login.py", "new_path": "timesketch/lib/analyzers/login.py", "diff": "@@ -184,7 +184,7 @@ class LoginSketchPlugin(interface.BaseSketchAnalyzer):\ntags_to_add.append('logon-event')\nlogin_counter += 1\n- elif identifier == 4634 or identifier == 4647:\n+ elif identifier in (4634, 4647):\nattribute_dict = parse_evtx_logoff_event(strings)\nif not attribute_dict:\ncontinue\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/phishy_domains_test.py", "new_path": "timesketch/lib/analyzers/phishy_domains_test.py", "diff": "\"\"\"Tests for DomainsPlugin.\"\"\"\nfrom __future__ import unicode_literals\n-from flask import current_app\nimport mock\nfrom datasketch.minhash import MinHash\n+from flask import current_app\nfrom timesketch.lib.analyzers import phishy_domains\nfrom timesketch.lib.testlib import BaseTest\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/similarity_scorer.py", "new_path": "timesketch/lib/analyzers/similarity_scorer.py", "diff": "@@ -133,7 +133,7 @@ class SimilarityScorer(interface.BaseIndexAnalyzer):\n\"\"\"\n# Exit early if there is no data_type to process.\nif not self._config:\n- return\n+ return None\n# Event generator for streaming results.\nevents = self.event_stream(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/google_auth_test.py", "new_path": "timesketch/lib/google_auth_test.py", "diff": "@@ -19,13 +19,14 @@ import time\nimport mock\nimport jwt\n+from cryptography.hazmat.backends.openssl.rsa import _RSAPublicKey\n+\nfrom timesketch.lib.testlib import BaseTest\nfrom timesketch.lib.google_auth import validate_jwt\nfrom timesketch.lib.google_auth import get_public_key_for_jwt\nfrom timesketch.lib.google_auth import JwtValidationError\nfrom timesketch.lib.google_auth import JwtKeyError\n-from cryptography.hazmat.backends.openssl.rsa import _RSAPublicKey\n# openssl ecparam -genkey -name prime256v1 -noout -out ec_private.pem\nMOCK_EC_PRIVATE_KEY = \"\"\"\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/utils.py", "new_path": "timesketch/lib/utils.py", "diff": "@@ -25,9 +25,9 @@ import smtplib\nimport sys\nimport time\n+from dateutil import parser\nfrom flask import current_app\n-from dateutil import parser\n# Set CSV field size limit to systems max value.\ncsv.field_size_limit(sys.maxsize)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -291,7 +291,7 @@ class SearchTemplateManager(Command):\nfor search_template in search_templates:\nname = search_template['name']\n- query_string = search_template['query_string'],\n+ query_string = search_template['query_string']\nquery_dsl = search_template['query_dsl']\n# Skip search template if already exits.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/views/auth.py", "new_path": "timesketch/views/auth.py", "diff": "@@ -218,3 +218,5 @@ def google_openid_connect():\n# Log the user in and setup the session.\nif current_user.is_authenticated:\nreturn redirect(request.args.get('next') or '/')\n+\n+ return abort(HTTP_STATUS_CODE_BAD_REQUEST)\n" } ]
Python
Apache License 2.0
google/timesketch
Multiple changes for code flagged by pylint 2.1.1 (#833)
263,093
18.02.2019 18:05:22
-3,600
a4837f70d4bc2bbdfa78e8620db3b77208195f1d
remove u' from docker scripts
[ { "change_type": "MODIFY", "old_path": "docker/docker-entrypoint.sh", "new_path": "docker/docker-entrypoint.sh", "diff": "# Run the container the default way\nif [ \"$1\" = 'timesketch' ]; then\n# Set SECRET_KEY in /etc/timesketch.conf if it isn't already set\n- if grep -q \"SECRET_KEY = u'<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\n+ if grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\nOPENSSL_RAND=$( openssl rand -base64 32 )\n# Using the pound sign as a delimiter to avoid problems with / being output from openssl\n- sed -i 's#SECRET_KEY = u\\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = u\\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch.conf\n+ sed -i 's#SECRET_KEY = \\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = \\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch.conf\nfi\n# Set up the Postgres connection\n@@ -20,7 +20,7 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Elastic connection\nif [ $ELASTIC_ADDRESS ] && [ $ELASTIC_PORT ]; then\n- sed -i 's#ELASTIC_HOST = u\\x27127.0.0.1\\x27#ELASTIC_HOST = u\\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch.conf\n+ sed -i 's#ELASTIC_HOST = \\x27127.0.0.1\\x27#ELASTIC_HOST = \\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch.conf\nsed -i 's#ELASTIC_PORT = 9200#ELASTIC_PORT = '$ELASTIC_PORT'#' /etc/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\n@@ -40,7 +40,7 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Neo4j connection\nif [ $NEO4J_ADDRESS ] && [ $NEO4J_PORT ]; then\nsed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch.conf\n- sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = u\\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch.conf\n+ sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch.conf\nsed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\n" }, { "change_type": "MODIFY", "old_path": "docker/timesketch-dev-entrypoint.sh", "new_path": "docker/timesketch-dev-entrypoint.sh", "diff": "@@ -40,10 +40,10 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/config/* /etc/timesketch/\n# Set SECRET_KEY in /etc/timesketch.conf if it isn't already set\n- if grep -q \"SECRET_KEY = u'<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\n+ if grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\nOPENSSL_RAND=$( openssl rand -base64 32 )\n# Using the pound sign as a delimiter to avoid problems with / being output from openssl\n- sed -i 's#SECRET_KEY = u\\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = u\\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch.conf\n+ sed -i 's#SECRET_KEY = \\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = \\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch.conf\nfi\n# Set up the Postgres connection\n@@ -57,7 +57,7 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Elastic connection\nif [ $ELASTIC_ADDRESS ] && [ $ELASTIC_PORT ]; then\n- sed -i 's#ELASTIC_HOST = u\\x27127.0.0.1\\x27#ELASTIC_HOST = u\\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch.conf\n+ sed -i 's#ELASTIC_HOST = \\x27127.0.0.1\\x27#ELASTIC_HOST = \\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch.conf\nsed -i 's#ELASTIC_PORT = 9200#ELASTIC_PORT = '$ELASTIC_PORT'#' /etc/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\n@@ -77,7 +77,7 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Neo4j connection\nif [ $NEO4J_ADDRESS ] && [ $NEO4J_PORT ]; then\nsed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch.conf\n- sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = u\\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch.conf\n+ sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch.conf\nsed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\n" } ]
Python
Apache License 2.0
google/timesketch
remove u' from docker scripts (#835)
263,093
21.02.2019 08:14:18
18,000
01f73cff6933017ee65c2ea335c452f094116443
Support re flags
[ { "change_type": "MODIFY", "old_path": "config/features.yaml", "new_path": "config/features.yaml", "diff": "# store_as:\n# re:\n# # Optional fields.\n+# re_flags: []\n# emojis: []\n# tags: []\n# create_view: False\n#\n# Each definition needs to define either a query_string or a query_dsl.\n#\n+# re_flags is a list of flags as strings from the re module. These include:\n+# - DEBUG\n+# - DOTALL\n+# - IGNORECASE\n+# - LOCALE\n+# - MULTILINE\n+# - TEMPLATE\n+# - UNICODE\n+# - VERBOSE\n+#\n# The fields tags and emojis are optional.\n#\n# The field store_as defines the name of the attribute the feature is\n@@ -41,6 +52,7 @@ email_addresses:\nattribute: 'message'\nstore_as: 'email_address'\nre: '([a-zA-Z0-9_\\.+\\-]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-\\.]+)'\n+ re_flags: []\naggregate: True\ngmail_accounts:\n@@ -48,6 +60,7 @@ gmail_accounts:\nattribute: 'title'\nstore_as: 'found_account'\nre: '.* - (.*?@.*?) - .*?$'\n+ re_flags: []\naggregate: True\ntags: ['Gmail Account']\nemojis: ['ID_BUTTON']\n@@ -58,6 +71,7 @@ github_accounts:\nattribute: 'url'\nstore_as: 'found_account'\nre: 'https://github.com/users/([A-z-\\d]{1,39})'\n+ re_flags: []\naggregate: True\ntags: ['Github Account']\nemojis: ['ID_BUTTON']\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/feature_extraction.py", "new_path": "timesketch/lib/analyzers/feature_extraction.py", "diff": "@@ -76,11 +76,25 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\ntags = config.get('tags', [])\nexpression_string = config.get('re')\n+ expression_flags = config.get('re_flags')\nif not expression_string:\nlogging.warning('No regular expression defined.')\nreturn ''\n+\n+ if expression_flags:\n+ flags = set()\n+ for flag in expression_flags:\n+ try:\n+ flags.add(getattr(re, flag))\n+ except AttributeError:\n+ logging.warning('Unknown regular expression flag defined.')\n+ return ''\n+ re_flag = sum(flags)\n+ else:\n+ re_flag = 0\n+\ntry:\n- expression = re.compile(expression_string)\n+ expression = re.compile(expression_string, flags=re_flag)\nexcept re.error as exception:\n# pylint: disable=logging-format-interpolation\nlogging.warning((\n@@ -101,7 +115,7 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\nfor event in events:\nattribute_field = event.source.get(attribute)\nif isinstance(attribute_field, six.text_type):\n- attribute_value = attribute_field.lower()\n+ attribute_value = attribute_field\nelif isinstance(attribute_field, (list, tuple)):\nattribute_value = ','.join(attribute_field)\nelif isinstance(attribute_field, (int, float)):\n" } ]
Python
Apache License 2.0
google/timesketch
Support re flags (#837)
263,093
21.02.2019 08:14:40
18,000
a006b39962fb856716092e9502555412d5b9d71c
Check if user exist
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -253,6 +253,12 @@ def run_email_result_task(index_name, sketch_id=None):\nsearchindex = SearchIndex.query.filter_by(index_name=index_name).first()\nsketch = None\n+ try:\n+ to_username = searchindex.user.username\n+ except AttributeError:\n+ logging.warning('No user to send email to.')\n+ return ''\n+\nif sketch_id:\nsketch = Sketch.query.get(sketch_id)\n@@ -281,8 +287,6 @@ def run_email_result_task(index_name, sketch_id=None):\nbody = body + '<br><br><b>Views</b><br>' + '<br>'.join(\nview_links)\n- to_username = searchindex.user.username\n-\ntry:\nsend_email(subject, body, to_username, use_html=True)\nexcept RuntimeError as e:\n" } ]
Python
Apache License 2.0
google/timesketch
Check if user exist (#838)
263,132
18.03.2019 05:17:21
25,200
d0bd0f43509cf96d86c5e89f10eb2eb96e5c6873
Linkedin account extraction * Linkedin account extraction Extracting linkedin accounts from profile edit URL * Update features.yaml * acting on feedback * Changed tag
[ { "change_type": "MODIFY", "old_path": "config/features.yaml", "new_path": "config/features.yaml", "diff": "@@ -75,3 +75,14 @@ github_accounts:\naggregate: True\ntags: ['Github Account']\nemojis: ['ID_BUTTON']\n+\n+# Linkedin account extraction from profile edit url\n+linkedin_accounts:\n+ query_string: 'source_short:\"WEBHIST\" AND\n+ url:\"https://www.linkedin.com/in/\" AND url:\"/edit/\"'\n+ attribute: 'url'\n+ store_as: 'found_account'\n+ re: 'https://www.linkedin.com/in/([A-z-\\d]{5,32})/edit/'\n+ aggregate: True\n+ tags: ['linkedin-account']\n+ emojis: ['ID_BUTTON']\n" } ]
Python
Apache License 2.0
google/timesketch
Linkedin account extraction (#839) * Linkedin account extraction Extracting linkedin accounts from profile edit URL * Update features.yaml * acting on feedback * Changed tag
263,178
20.03.2019 19:30:21
-3,600
a4ddc99ad5454577a6f9adeada6f8fa4ec5d2b7f
Moved pylint to stand-alone CI test target
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "+matrix:\n+ include:\n+ - name: \"Pylint on Ubuntu Xenial (16.04) with Python 3.5\"\n+ env: TARGET=\"pylint\"\n+ os: linux\n+ dist: xenial\n+ group: edge\nlanguage: python\n-python:\n- - '2.7'\n- - '3.6'\n+ python: 3.5\n+ node_js: '8'\n+ virtualenv:\n+ system_site_packages: true\n+ - name: \"Ubuntu Xenial (16.04) with Python 2.7\"\n+ env: TARGET=\"linux-python27\"\n+ os: linux\n+ dist: xenial\n+ group: edge\n+ language: python\n+ python: 2.7\n+ node_js: '8'\n+ - name: \"Ubuntu Xenial (16.04) with Python 3.6\"\n+ env: TARGET=\"linux-python36\"\n+ os: linux\n+ dist: xenial\n+ group: edge\n+ language: python\n+ python: 3.6\nnode_js: '8'\ncache:\n- yarn\n- pip\n-\ninstall:\n- - pip install .\n+- pip install -r requirements.txt\n+- if test ${TARGET} = \"pylint\"; then pip install astroid==1.5.3 pylint==1.7.2; fi\n- yarn install\n-\nscript:\n- - ./run_tests.py --full\n- - yarn run build\n+- ./config/travis/run_with_timeout.sh 30 ./config/travis/runtests.sh\n" }, { "change_type": "ADD", "old_path": null, "new_path": "config/travis/run_with_timeout.sh", "diff": "+#!/bin/bash\n+#\n+# Script to run commands on a Travis-CI test VM that otherwise would time out\n+# after 10 minutes. This replaces travis_wait and outputs stdout of the command\n+# running.\n+#\n+# This file is generated by l2tdevtools update-dependencies.py, any dependency\n+# related changes should be made in dependencies.ini.\n+\n+# Exit on error.\n+set -e\n+\n+# Usage: ./run_with_timeout.sh [TIMEOUT] [COMMAND] [OPTION] [...]\n+\n+TIMEOUT=$1;\n+shift\n+\n+# Launch a command in the background.\n+$* &\n+\n+PID_COMMAND=$!;\n+\n+# Probe the command every minute.\n+MINUTES=0;\n+\n+while kill -0 ${PID_COMMAND} >/dev/null 2>&1;\n+do\n+ # Print to stdout, seeing this prints a space and a backspace\n+ # there is no visible trace.\n+ echo -n -e \" \\b\";\n+\n+ if test ${MINUTES} -ge ${TIMEOUT};\n+ then\n+ kill -9 ${PID_COMMAND} >/dev/null 2>&1;\n+\n+ echo -e \"\\033[0;31m[ERROR] command: $* timed out after: ${MINUTES} minute(s).\\033[0m\";\n+\n+ exit 1;\n+ fi\n+ MINUTES=$(( ${MINUTES} + 1 ));\n+\n+ sleep 60;\n+done\n+\n+wait ${PID_COMMAND};\n+\n+exit $?;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "config/travis/runtests.sh", "diff": "+#!/bin/bash\n+#\n+# Script to run tests on Travis-CI.\n+#\n+# This file is generated by l2tdevtools update-dependencies.py, any dependency\n+# related changes should be made in dependencies.ini.\n+\n+# Exit on error.\n+set -e;\n+\n+if test \"${TARGET}\" = \"pylint\";\n+then\n+ pylint --version\n+\n+ for FILE in `find run_tests.py setup.py config timesketch tests -name \\*.py`;\n+ do\n+ echo \"Checking: ${FILE}\";\n+\n+ pylint --rcfile=.pylintrc ${FILE};\n+ done\n+\n+ for FILE in `find api_client -name \\*.py`;\n+ do\n+ echo \"Checking: ${FILE}\";\n+\n+ PYTHONPATH=api_client/python pylint --rcfile=.pylintrc ${FILE};\n+ done\n+\n+elif test \"${TRAVIS_OS_NAME}\" = \"linux\";\n+then\n+ python ./run_tests.py --full\n+\n+ yarn run build\n+fi\n" }, { "change_type": "MODIFY", "old_path": "requirements.in", "new_path": "requirements.in", "diff": "@@ -32,7 +32,6 @@ altair>=2.4.1\nFlask-Testing\nnose\nmock\n-pylint\ncoverage\n# Remove the following when pip-sync finally stops deleting pkg_resources.\n" }, { "change_type": "MODIFY", "old_path": "requirements.txt", "new_path": "requirements.txt", "diff": "@@ -3,9 +3,7 @@ altair==2.4.1\namqp==2.2.1 # via kombu\naniso8601==1.2.1 # via flask-restful\nasn1crypto==0.24.0 # via cryptography\n-astroid==1.5.3 # via pylint\nattrs==18.2.0 # via jsonschema\n-backports.functools-lru-cache==1.4 # via astroid, pylint\nbcrypt==3.1.3 # via flask-bcrypt\nbilliard==3.5.0.3 # via celery\nblinker==1.4\n@@ -14,7 +12,7 @@ certifi==2017.7.27.1 # via requests\ncffi==1.10.0 # via bcrypt, cryptography\nchardet==3.0.4 # via requests\nclick==6.7 # via flask\n-configparser==3.5.0 # via entrypoints, pylint\n+configparser==3.5.0 # via entrypoints\ncoverage==4.4.1\ncryptography==2.4.1\ndatasketch==1.2.5\n@@ -34,7 +32,6 @@ funcsigs==1.0.2 # via mock\ngunicorn==19.7.1\nidna==2.6 # via cryptography, requests\nipaddress==1.0.22 # via cryptography\n-isort==4.2.15 # via pylint\nitsdangerous==0.24 # via flask\njinja2==2.10 # via altair, flask\njsonschema==3.0.0 # via altair\n@@ -42,7 +39,6 @@ kombu==4.1.0 # via celery\nlazy-object-proxy==1.3.1 # via astroid\nmako==1.0.7 # via alembic\nmarkupsafe==1.0 # via jinja2, mako\n-mccabe==0.6.1 # via pylint\nmock==2.0.0\nneo4jrestclient==2.1.1\nnose==1.3.7\n@@ -52,7 +48,6 @@ parameterized==0.6.1\npbr==3.1.1 # via mock\npycparser==2.18 # via cffi\npyjwt==1.6.4\n-pylint==1.7.2\npyrsistent==0.14.11 # via jsonschema\npython-dateutil==2.6.1\npython-editor==1.0.3 # via alembic\n@@ -60,8 +55,7 @@ pytz==2017.2 # via celery, flask-restful, pandas\npyyaml==4.2b4\nredis==2.10.6\nrequests==2.20.1\n-singledispatch==3.4.0.3 # via astroid, pylint\n-six==1.12.0 # via altair, astroid, bcrypt, cryptography, flask-restful, jsonschema, mock, pylint, pyrsistent, python-dateutil, singledispatch\n+six==1.12.0 # via altair, bcrypt, cryptography, flask-restful, jsonschema, mock, pyrsistent, python-dateutil\nsqlalchemy==1.1.13\ntoolz==0.9.0 # via altair\ntyping==3.6.6 # via altair\n" }, { "change_type": "MODIFY", "old_path": "run_tests.py", "new_path": "run_tests.py", "diff": "@@ -21,21 +21,9 @@ def run_python_tests(coverage=False):\nfinally:\nsubprocess.check_call(['rm', '-f', '.coverage'])\n-def run_python_linter():\n- subprocess.check_call(['pylint', 'timesketch'])\n- subprocess.check_call(\n- 'PYTHONPATH=api_client/python/:$PYTHONPATH'\n- + ' pylint timesketch_api_client',\n- shell=True,\n- )\n- subprocess.check_call(['pylint', 'run_tests'])\n- subprocess.check_call(['pylint', 'setup'])\n-\ndef run_python(args):\nif not args.no_tests:\nrun_python_tests(coverage=args.coverage)\n- if not args.no_lint:\n- run_python_linter()\ndef run_javascript_tests(coverage=False):\nif coverage:\n" }, { "change_type": "UNKNOWN", "old_path": "setup.py", "new_path": "setup.py", "diff": "" } ]
Python
Apache License 2.0
google/timesketch
Moved pylint to stand-alone CI test target (#831)
263,178
20.03.2019 21:07:27
-3,600
de8f4e383edeb504b689c0932bed00a115f0ba71
Updated CI test to use pylint 2.2.2
[ { "change_type": "MODIFY", "old_path": ".pylintrc", "new_path": ".pylintrc", "diff": "@@ -76,7 +76,7 @@ load-plugins=\n# W1201: Specify string format arguments as logging function parameters\n# W0201: Variables defined initially outside the scope of __init__ (reconsider this, added by Kristinn).\n#disable=C0103,C0111,C0302,F0401,I0010,I0011,R0201,R0801,R0901,R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,R0921,R0922,R0924,W0122,W0141,W0142,W0402,W0404,W0511,W0603,W0703,W1201,W0201\n-disable=C0103,C0302,F0401,I0010,I0011,R0201,R0801,R0901,R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,R0921,R0922,R0924,W0122,W0141,W0142,W0402,W0404,W0511,W0603,W0703,W1201,W0201,R0401,no-member,useless-super-delegation\n+disable=C0103,C0302,F0401,I0010,I0011,R0201,R0801,R0901,R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,R0921,R0922,R0924,W0122,W0141,W0142,W0402,W0404,W0511,W0603,W0703,W1201,W0201,R0401,no-member,useless-super-delegation,useless-object-inheritance\n[REPORTS]\n" }, { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -30,8 +30,8 @@ cache:\n- yarn\n- pip\ninstall:\n+- ./config/travis/install.sh\n- pip install -r requirements.txt\n-- if test ${TARGET} = \"pylint\"; then pip install astroid==1.5.3 pylint==1.7.2; fi\n- yarn install\nscript:\n- ./config/travis/run_with_timeout.sh 30 ./config/travis/runtests.sh\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -17,6 +17,7 @@ from __future__ import unicode_literals\nimport json\nimport uuid\n+# pylint: disable=wrong-import-order\nimport bs4\nimport requests\n" }, { "change_type": "ADD", "old_path": null, "new_path": "config/travis/install.sh", "diff": "+#!/bin/bash\n+#\n+# Script to set up Travis-CI test VM.\n+#\n+# This file is generated by l2tdevtools update-dependencies.py any dependency\n+# related changes should be made in dependencies.ini.\n+\n+# Exit on error.\n+set -e;\n+if test ${TRAVIS_OS_NAME} = \"linux\" && test ${TARGET} != \"jenkins\";\n+then\n+ if test ${TARGET} = \"pylint\";\n+ then\n+ sudo add-apt-repository ppa:gift/pylint3 -y;\n+ fi\n+\n+ sudo apt-get update -q;\n+\n+ if test ${TARGET} = \"pylint\";\n+ then\n+ sudo apt-get install -y pylint;\n+ fi\n+fi\n" }, { "change_type": "MODIFY", "old_path": "config/travis/runtests.sh", "new_path": "config/travis/runtests.sh", "diff": "@@ -12,7 +12,7 @@ if test \"${TARGET}\" = \"pylint\";\nthen\npylint --version\n- for FILE in `find run_tests.py setup.py config timesketch tests -name \\*.py`;\n+ for FILE in `find run_tests.py setup.py api_client config timesketch -name \\*.py`;\ndo\necho \"Checking: ${FILE}\";\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 flask import current_app\nfrom elasticsearch import Elasticsearch\n+from flask import current_app\nimport pandas\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_timeframe.py", "new_path": "timesketch/lib/analyzers/browser_timeframe.py", "diff": "@@ -127,7 +127,7 @@ def get_active_hours(frame):\nhours = sorted(hours)\nhour_len = len(hours)\n- if hour_len >= 3 and hour_len <= 12:\n+ if 3 <= hour_len <= 12:\nthresholds[threshold] = hour_len\nthreshold_counter = collections.Counter(thresholds)\n" } ]
Python
Apache License 2.0
google/timesketch
Updated CI test to use pylint 2.2.2 (#852)
263,178
24.03.2019 13:21:30
-3,600
33f48b4262b5e1ea744ec51b4d8d8a318ea49bab
Changes to Travis-CI configuration to use installation script
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -10,7 +10,7 @@ matrix:\nnode_js: '8'\nvirtualenv:\nsystem_site_packages: true\n- - name: \"Ubuntu Xenial (16.04) with Python 2.7\"\n+ - name: \"Ubuntu Xenial (16.04) with Python 2.7 (pip)\"\nenv: TARGET=\"linux-python27\"\nos: linux\ndist: xenial\n@@ -18,7 +18,7 @@ matrix:\nlanguage: python\npython: 2.7\nnode_js: '8'\n- - name: \"Ubuntu Xenial (16.04) with Python 3.6\"\n+ - name: \"Ubuntu Xenial (16.04) with Python 3.6 (pip)\"\nenv: TARGET=\"linux-python36\"\nos: linux\ndist: xenial\n@@ -26,12 +26,30 @@ matrix:\nlanguage: python\npython: 3.6\nnode_js: '8'\n+ - name: \"Ubuntu Bionic (18.04) (Docker) with Python 2.7\"\n+ env: UBUNTU_VERSION=\"18.04\"\n+ os: linux\n+ dist: xenial\n+ sudo: required\n+ group: edge\n+ language: python\n+ python: 2.7\n+ services:\n+ - docker\n+ - name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6\"\n+ env: UBUNTU_VERSION=\"18.04\"\n+ os: linux\n+ dist: xenial\n+ sudo: required\n+ group: edge\n+ language: python\n+ python: 3.6\n+ services:\n+ - docker\ncache:\n- yarn\n- pip\ninstall:\n- ./config/travis/install.sh\n-- pip install -r requirements.txt\n-- yarn install\nscript:\n- ./config/travis/run_with_timeout.sh 30 ./config/travis/runtests.sh\n" }, { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "# This file is generated by l2tdevtools update-dependencies.py any dependency\n# related changes should be made in dependencies.ini.\n+DPKG_PYTHON2_DEPENDENCIES=\"python-alembic python-altair python-amqp python-aniso8601 python-asn1crypto python-attr python-bcrypt python-billiard python-blinker python-bs4 python-celery python-certifi python-cffi python-chardet python-click python-configparser python-cryptography python-datasketch python-dateutil python-editor python-elasticsearch python-elasticsearch5 python-entrypoints python-enum34 python-flask python-flask-bcrypt python-flask-login python-flask-migrate python-flask-restful python-flask-script python-flask-sqlalchemy python-flask-wtf python-gunicorn python-idna python-ipaddress python-itsdangerous python-jinja2 python-jsonschema python-jwt python-kombu python-mako python-markupsafe python-neo4jrestclient python-numpy python-pandas python-parameterized python-pycparser python-pyrsistent python-redis python-requests python-six python-sqlalchemy python-toolz python-typing python-tz python-urllib3 python-vine python-werkzeug python-wtforms python-yaml\";\n+\n+DPKG_PYTHON2_TEST_DEPENDENCIES=\"python-coverage python-flask-testing python-funcsigs python-mock python-nose python-pbr\";\n+\n+DPKG_PYTHON3_DEPENDENCIES=\"python3-alembic python3-altair python3-amqp python3-aniso8601 python3-asn1crypto python3-attr python3-bcrypt python3-billiard python3-blinker python3-bs4 python3-celery python3-certifi python3-cffi python3-chardet python3-click python3-cryptography python3-datasketch python3-dateutil python3-editor python3-elasticsearch python3-elasticsearch5 python3-entrypoints python3-flask python3-flask-bcrypt python3-flask-login python3-flask-migrate python3-flask-restful python3-flask-script python3-flask-sqlalchemy python3-flask-wtf python3-gunicorn python3-idna python3-ipaddress python3-itsdangerous python3-jinja2 python3-jsonschema python3-jwt python3-kombu python3-mako python3-markupsafe python3-neo4jrestclient python3-numpy python3-pandas python3-parameterized python3-pycparser python3-pyrsistent python3-redis python3-requests python3-six python3-sqlalchemy python3-toolz python3-tz python3-urllib3 python3-vine python3-werkzeug python3-wtforms python3-yaml\";\n+\n+DPKG_PYTHON3_TEST_DEPENDENCIES=\"python3-flask-testing python3-mock python3-nose python3-pbr python3-setuptools\";\n+\n# Exit on error.\nset -e;\n-if test ${TRAVIS_OS_NAME} = \"linux\" && test ${TARGET} != \"jenkins\";\n+\n+if test -n \"${UBUNTU_VERSION}\";\n+then\n+ CONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\n+\n+ docker pull ubuntu:${UBUNTU_VERSION};\n+\n+ docker run --name=${CONTAINER_NAME} --detach -i ubuntu:${UBUNTU_VERSION};\n+\n+ docker exec ${CONTAINER_NAME} apt-get update -q;\n+ docker exec ${CONTAINER_NAME} apt-get install -y software-properties-common;\n+\n+ docker exec ${CONTAINER_NAME} add-apt-repository universe -y;\n+ docker exec ${CONTAINER_NAME} add-apt-repository ppa:gift/dev -y;\n+\n+ docker exec ${CONTAINER_NAME} apt-key adv --fetch-keys https://dl.yarnpkg.com/debian/pubkey.gpg;\n+ docker exec ${CONTAINER_NAME} add-apt-repository \"deb https://dl.yarnpkg.com/debian/ stable main\";\n+\n+ if test ${TRAVIS_PYTHON_VERSION} = \"2.7\";\nthen\n+ docker exec ${CONTAINER_NAME} sh -c \"DEBIAN_FRONTEND=noninteractive apt-get install -y git yarn python ${DPKG_PYTHON2_DEPENDENCIES} ${DPKG_PYTHON2_TEST_DEPENDENCIES}\";\n+ else\n+ docker exec ${CONTAINER_NAME} sh -c \"DEBIAN_FRONTEND=noninteractive apt-get install -y git yarn python3 ${DPKG_PYTHON3_DEPENDENCIES} ${DPKG_PYTHON3_TEST_DEPENDENCIES}\";\n+ fi\n+\n+ docker cp ../timesketch ${CONTAINER_NAME}:/\n+\n+ docker exec ${CONTAINER_NAME} sh -c \"cd timesketch && yarn install\";\n+\n+elif test ${TRAVIS_OS_NAME} = \"linux\" && test ${TARGET} != \"jenkins\";\n+then\n+ pip install -r requirements.txt;\n+\nif test ${TARGET} = \"pylint\";\nthen\nsudo add-apt-repository ppa:gift/pylint3 -y;\n@@ -20,4 +59,5 @@ then\nthen\nsudo apt-get install -y pylint;\nfi\n+ yarn install;\nfi\n" }, { "change_type": "MODIFY", "old_path": "config/travis/runtests.sh", "new_path": "config/travis/runtests.sh", "diff": "@@ -26,6 +26,17 @@ then\nPYTHONPATH=api_client/python pylint --rcfile=.pylintrc ${FILE};\ndone\n+elif test -n \"${UBUNTU_VERSION}\";\n+then\n+ CONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\n+\n+ if test ${TRAVIS_PYTHON_VERSION} = \"2.7\";\n+ then\n+ docker exec ${CONTAINER_NAME} sh -c \"export LANG=en_US.UTF-8; cd timesketch && nosetests\";\n+ else\n+ docker exec ${CONTAINER_NAME} sh -c \"export LANG=en_US.UTF-8; cd timesketch && nosetests3\";\n+ fi\n+\nelif test \"${TRAVIS_OS_NAME}\" = \"linux\";\nthen\npython ./run_tests.py --full\n" } ]
Python
Apache License 2.0
google/timesketch
Changes to Travis-CI configuration to use installation script (#832)
263,178
03.04.2019 12:01:45
-7,200
44ee27b283900dbb8713fc9fe494661bc18a1cb4
Added l2tdevtools configuration files and generated dependency files
[ { "change_type": "ADD", "old_path": null, "new_path": "config/linux/gift_ppa_install.sh", "diff": "+#!/usr/bin/env bash\n+#\n+# This file is generated by l2tdevtools update-dependencies.py any dependency\n+# related changes should be made in dependencies.ini.\n+\n+# Exit on error.\n+set -e\n+\n+# Dependencies for running timesketch, alphabetized, one per line.\n+# This should not include packages only required for testing or development.\n+PYTHON2_DEPENDENCIES=\"python-alembic\n+ python-altair\n+ python-amqp\n+ python-aniso8601\n+ python-asn1crypto\n+ python-attr\n+ python-bcrypt\n+ python-billiard\n+ python-blinker\n+ python-bs4\n+ python-celery\n+ python-certifi\n+ python-cffi\n+ python-chardet\n+ python-click\n+ python-configparser\n+ python-cryptography\n+ python-datasketch\n+ python-dateutil\n+ python-editor\n+ python-elasticsearch\n+ python-elasticsearch5\n+ python-entrypoints\n+ python-enum34\n+ python-flask\n+ python-flask-bcrypt\n+ python-flask-login\n+ python-flask-migrate\n+ python-flask-restful\n+ python-flask-script\n+ python-flask-sqlalchemy\n+ python-flask-wtf\n+ python-gunicorn\n+ python-idna\n+ python-ipaddress\n+ python-itsdangerous\n+ python-jinja2\n+ python-jsonschema\n+ python-jwt\n+ python-kombu\n+ python-mako\n+ python-markupsafe\n+ python-neo4jrestclient\n+ python-numpy\n+ python-pandas\n+ python-parameterized\n+ python-pycparser\n+ python-pyrsistent\n+ python-redis\n+ python-requests\n+ python-six\n+ python-sqlalchemy\n+ python-toolz\n+ python-typing\n+ python-tz\n+ python-urllib3\n+ python-vine\n+ python-werkzeug\n+ python-wtforms\n+ python-yaml\";\n+\n+# Additional dependencies for running tests, alphabetized, one per line.\n+TEST_DEPENDENCIES=\"python-coverage\n+ python-flask-testing\n+ python-funcsigs\n+ python-mock\n+ python-nose\n+ python-pbr\";\n+\n+\n+sudo add-apt-repository ppa:gift/dev -y\n+sudo apt-get update -q\n+sudo apt-get install -y ${PYTHON2_DEPENDENCIES}\n+\n+if [[ \"$*\" =~ \"include-test\" ]]; then\n+ sudo apt-get install -y ${TEST_DEPENDENCIES}\n+fi\n" }, { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "@@ -67,6 +67,7 @@ then\nelif test ${TRAVIS_OS_NAME} = \"linux\" && test ${TARGET} != \"jenkins\";\nthen\npip install -r requirements.txt;\n+ pip install -r test_requirements.txt;\nyarn install;\nfi\n" }, { "change_type": "ADD", "old_path": null, "new_path": "dependencies.ini", "diff": "+[alembic]\n+dpkg_name: python-alembic\n+minimum_version: 0.9.5\n+rpm_name: python2-alembic\n+\n+[altair]\n+dpkg_name: python-altair\n+minimum_version: 2.4.1\n+rpm_name: python2-altair\n+\n+[amqp]\n+dpkg_name: python-amqp\n+minimum_version: 2.2.1\n+rpm_name: python2-amqp\n+\n+[aniso8601]\n+dpkg_name: python-aniso8601\n+minimum_version: 1.2.1\n+rpm_name: python2-aniso8601\n+\n+[asn1crypto]\n+dpkg_name: python-asn1crypto\n+minimum_version: 0.24.0\n+rpm_name: python2-asn1crypto\n+\n+[attrs]\n+dpkg_name: python-attr\n+minimum_version: 19.1.0\n+rpm_name: python2-attrs\n+\n+[bcrypt]\n+dpkg_name: python-bcrypt\n+minimum_version: 3.1.3\n+rpm_name: python2-bcrypt\n+\n+[billiard]\n+dpkg_name: python-billiard\n+minimum_version: 3.5.0.3\n+rpm_name: python2-billiard\n+\n+[blinker]\n+dpkg_name: python-blinker\n+minimum_version: 1.4\n+rpm_name: python2-blinker\n+\n+[bs4]\n+dpkg_name: python-bs4\n+minimum_version: 4.6.3\n+pypi_name: beautifulsoup4\n+rpm_name: python2-beautifulsoup4\n+version_property: __version__\n+\n+[celery]\n+dpkg_name: python-celery\n+minimum_version: 4.1.0\n+rpm_name: python2-celery\n+\n+[certifi]\n+dpkg_name: python-certifi\n+minimum_version: 2017.7.27.1\n+rpm_name: python2-certifi\n+\n+[cffi]\n+dpkg_name: python-cffi\n+minimum_version: 1.10.0\n+rpm_name: python2-cffi\n+\n+[chardet]\n+dpkg_name: python-chardet\n+minimum_version: 3.0.4\n+rpm_name: python2-chardet\n+\n+[Click]\n+dpkg_name: python-click\n+minimum_version: 6.7\n+rpm_name: python2-click\n+\n+[configparser]\n+dpkg_name: python-configparser\n+minimum_version: 3.5.0\n+python2_only: true\n+rpm_name: python2-configparser\n+\n+[cryptography]\n+dpkg_name: python-cryptography\n+minimum_version: 2.4.1\n+rpm_name: python2-cryptography\n+\n+[datasketch]\n+dpkg_name: python-datasketch\n+minimum_version: 1.2.5\n+rpm_name: python2-datasketch\n+\n+[dateutil]\n+dpkg_name: python-dateutil\n+minimum_version: 2.6.1\n+pypi_name: python-dateutil\n+rpm_name: python2-dateutil\n+version_property: __version__\n+\n+[elasticsearch]\n+dpkg_name: python-elasticsearch\n+is_optional: true\n+l2tbinaries_name: elasticsearch-py\n+minimum_version: 6.0\n+pypi_name: elasticsearch\n+rpm_name: python-elasticsearch\n+version_property: __versionstr__\n+\n+[elasticsearch5]\n+dpkg_name: python-elasticsearch5\n+l2tbinaries_name: elasticsearch5-py\n+minimum_version: 5.4.0\n+pypi_name: elasticsearch5\n+rpm_name: python-elasticsearch5\n+version_property: __versionstr__\n+\n+[enum34]\n+dpkg_name: python-enum34\n+minimum_version: 1.1.6\n+python2_only: true\n+rpm_name: python2-enum34\n+\n+[entrypoints]\n+dpkg_name: python-entrypoints\n+minimum_version: 0.2.3\n+rpm_name: python2-entrypoints\n+\n+[Flask]\n+dpkg_name: python-flask\n+minimum_version: 1.0.2\n+rpm_name: python2-flask\n+\n+[Flask-Bcrypt]\n+dpkg_name: python-flask-bcrypt\n+minimum_version: 0.7.1\n+rpm_name: python2-flask-bcrypt\n+\n+[Flask-Login]\n+dpkg_name: python-flask-login\n+minimum_version: 0.4.0\n+rpm_name: python2-flask-login\n+\n+[Flask-Migrate]\n+dpkg_name: python-flask-migrate\n+minimum_version: 2.1.1\n+rpm_name: python2-flask-migrate\n+\n+[Flask-RESTful]\n+dpkg_name: python-flask-restful\n+minimum_version: 0.3.6\n+rpm_name: python2-flask-restful\n+\n+[Flask-Script]\n+dpkg_name: python-flask-script\n+minimum_version: 2.0.5\n+rpm_name: python2-flask-script\n+\n+[Flask-SQLAlchemy]\n+dpkg_name: python-flask-sqlalchemy\n+minimum_version: 2.2\n+rpm_name: python2-flask-sqlalchemy\n+\n+[Flask-WTF]\n+dpkg_name: python-flask-wtf\n+minimum_version: 0.14.2\n+rpm_name: python2-flask-wtf\n+\n+[gunicorn]\n+dpkg_name: python-gunicorn\n+minimum_version: 19.7.1\n+rpm_name: python2-gunicorn\n+\n+[idna]\n+dpkg_name: python-idna\n+minimum_version: 2.6\n+rpm_name: python2-idna\n+\n+[ipaddress]\n+dpkg_name: python-ipaddress\n+minimum_version: 1.0.22\n+rpm_name: python2-ipaddress\n+\n+[itsdangerous]\n+dpkg_name: python-itsdangerous\n+minimum_version: 0.24\n+rpm_name: python2-itsdangerous\n+\n+[Jinja2]\n+dpkg_name: python-jinja2\n+minimum_version: 2.10\n+rpm_name: python2-jinja2\n+\n+[jsonschema]\n+dpkg_name: python-jsonschema\n+minimum_version: 2.6.0\n+rpm_name: python2-jsonschema\n+\n+[kombu]\n+dpkg_name: python-kombu\n+minimum_version: 4.1.0\n+rpm_name:\n+\n+[Mako]\n+dpkg_name: python-mako\n+minimum_version: 1.0.7\n+rpm_name:\n+\n+[MarkupSafe]\n+dpkg_name: python-markupsafe\n+minimum_version: 1.0\n+rpm_name: python2-markupsafe\n+\n+[neo4jrestclient]\n+dpkg_name: python-neo4jrestclient\n+minimum_version: 2.1.1\n+rpm_name: python2-neo4jrestclient\n+\n+[numpy]\n+dpkg_name: python-numpy\n+minimum_version: 1.13.3\n+rpm_name: python2-numpy\n+\n+[pandas]\n+dpkg_name: python-pandas\n+minimum_version: 0.22.0\n+rpm_name: python2-pandas\n+\n+[parameterized]\n+dpkg_name: python-parameterized\n+minimum_version: 0.6.1\n+rpm_name: python2-parameterized\n+\n+[pycparser]\n+dpkg_name: python-pycparser\n+minimum_version: 2.18\n+rpm_name: python2-pycparser\n+\n+[PyJWT]\n+dpkg_name: python-jwt\n+minimum_version: 1.6.4\n+rpm_name: python2-jwt\n+\n+[pyrsistent]\n+dpkg_name: python-pyrsistent\n+minimum_version: 0.14.11\n+rpm_name: python2-pyrsistent\n+\n+[python-editor]\n+dpkg_name: python-editor\n+minimum_version: 1.0.3\n+rpm_name: python2-editor\n+\n+[pytz]\n+dpkg_name: python-tz\n+rpm_name: python2-pytz\n+version_property: __version__\n+\n+[redis]\n+dpkg_name: python-redis\n+minimum_version: 2.10.6\n+rpm_name: python2-redis\n+\n+[requests]\n+dpkg_name: python-requests\n+minimum_version: 2.20.1\n+rpm_name: python2-requests\n+\n+[six]\n+dpkg_name: python-six\n+minimum_version: 1.10.0\n+rpm_name: python2-six\n+\n+[SQLAlchemy]\n+dpkg_name: python-sqlalchemy\n+minimum_version: 1.1.13\n+rpm_name: python2-sqlalchemy\n+\n+[toolz]\n+dpkg_name: python-toolz\n+minimum_version: 0.8.2\n+rpm_name: python2-toolz\n+\n+[typing]\n+dpkg_name: python-typing\n+minimum_version: 3.6.2\n+python2_only: true\n+rpm_name: python2-typing\n+\n+[urllib3]\n+dpkg_name: python-urllib3\n+minimum_version: 1.24.1\n+rpm_name: python2-urllib3\n+\n+[vine]\n+dpkg_name: python-vine\n+minimum_version: 1.1.4\n+rpm_name: python2-vine\n+\n+[werkzeug]\n+dpkg_name: python-werkzeug\n+minimum_version: 0.14.1\n+rpm_name: python2-werkzeug\n+\n+[WTForms]\n+dpkg_name: python-wtforms\n+minimum_version: 2.1\n+rpm_name: python2-wtforms\n+\n+[yaml]\n+dpkg_name: python-yaml\n+l2tbinaries_name: PyYAML\n+minimum_version: 3.10\n+pypi_name: PyYAML\n+rpm_name: PyYAML\n+version_property: __version__\n" }, { "change_type": "MODIFY", "old_path": "requirements.txt", "new_path": "requirements.txt", "diff": "@@ -28,7 +28,6 @@ flask-sqlalchemy==2.2\nflask-testing==0.6.2\nflask-wtf==0.14.2\nflask==1.0.2\n-funcsigs==1.0.2 # via mock\ngunicorn==19.7.1\nidna==2.6 # via cryptography, requests\nipaddress==1.0.22 # via cryptography\n@@ -39,13 +38,10 @@ kombu==4.1.0 # via celery\nlazy-object-proxy==1.3.1 # via astroid\nmako==1.0.7 # via alembic\nmarkupsafe==1.0 # via jinja2, mako\n-mock==2.0.0\nneo4jrestclient==2.1.1\n-nose==1.3.7\nnumpy==1.13.3 # via altair, datasketch, pandas\npandas==0.24.1\nparameterized==0.6.1\n-pbr==3.1.1 # via mock\npycparser==2.18 # via cffi\npyjwt==1.6.4\npyrsistent==0.14.11 # via jsonschema\n@@ -55,7 +51,7 @@ pytz==2017.2 # via celery, flask-restful, pandas\npyyaml==4.2b4\nredis==2.10.6\nrequests==2.20.1\n-six==1.12.0 # via altair, bcrypt, cryptography, flask-restful, jsonschema, mock, pyrsistent, python-dateutil\n+six==1.12.0 # via altair, bcrypt, cryptography, flask-restful, jsonschema, pyrsistent, python-dateutil\nsqlalchemy==1.1.13\ntoolz==0.9.0 # via altair\ntyping==3.6.6 # via altair\n" }, { "change_type": "ADD", "old_path": null, "new_path": "setup.cfg", "diff": "+[metadata]\n+license_file = LICENSE\n+\n+[bdist_rpm]\n+release = 1\n+packager = Timesketch development team <timesketch-dev@googlegroups.com>\n+doc_files = AUTHORS\n+ LICENSE\n+build_requires = python2-setuptools\n+requires = Mako >= 1.0.7\n+ PyYAML >= 3.10\n+ kombu >= 4.1.0\n+ python-elasticsearch >= 6.0\n+ python-elasticsearch5 >= 5.4.0\n+ python2-alembic >= 0.9.5\n+ python2-altair >= 2.4.1\n+ python2-amqp >= 2.2.1\n+ python2-aniso8601 >= 1.2.1\n+ python2-asn1crypto >= 0.24.0\n+ python2-attrs >= 19.1.0\n+ python2-bcrypt >= 3.1.3\n+ python2-beautifulsoup4 >= 4.6.3\n+ python2-billiard >= 3.5.0.3\n+ python2-blinker >= 1.4\n+ python2-celery >= 4.1.0\n+ python2-certifi >= 2017.7.27.1\n+ python2-cffi >= 1.10.0\n+ python2-chardet >= 3.0.4\n+ python2-click >= 6.7\n+ python2-configparser >= 3.5.0\n+ python2-cryptography >= 2.4.1\n+ python2-datasketch >= 1.2.5\n+ python2-dateutil >= 2.6.1\n+ python2-editor >= 1.0.3\n+ python2-entrypoints >= 0.2.3\n+ python2-enum34 >= 1.1.6\n+ python2-flask >= 1.0.2\n+ python2-flask-bcrypt >= 0.7.1\n+ python2-flask-login >= 0.4.0\n+ python2-flask-migrate >= 2.1.1\n+ python2-flask-restful >= 0.3.6\n+ python2-flask-script >= 2.0.5\n+ python2-flask-sqlalchemy >= 2.2\n+ python2-flask-wtf >= 0.14.2\n+ python2-gunicorn >= 19.7.1\n+ python2-idna >= 2.6\n+ python2-ipaddress >= 1.0.22\n+ python2-itsdangerous >= 0.24\n+ python2-jinja2 >= 2.10\n+ python2-jsonschema >= 2.6.0\n+ python2-jwt >= 1.6.4\n+ python2-markupsafe >= 1.0\n+ python2-neo4jrestclient >= 2.1.1\n+ python2-numpy >= 1.13.3\n+ python2-pandas >= 0.22.0\n+ python2-parameterized >= 0.6.1\n+ python2-pycparser >= 2.18\n+ python2-pyrsistent >= 0.14.11\n+ python2-pytz\n+ python2-redis >= 2.10.6\n+ python2-requests >= 2.20.1\n+ python2-six >= 1.10.0\n+ python2-sqlalchemy >= 1.1.13\n+ python2-toolz >= 0.8.2\n+ python2-typing >= 3.6.2\n+ python2-urllib3 >= 1.24.1\n+ python2-vine >= 1.1.4\n+ python2-werkzeug >= 0.14.1\n+ python2-wtforms >= 2.1\n+\n+[bdist_wheel]\n+universal = 1\n+\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -61,4 +61,7 @@ setup(\ninstall_requires=[str(req.req) for req in parse_requirements(\n'requirements.txt', session=PipSession(),\n)],\n+ tests_require=[str(req.req) for req in parse_requirements(\n+ 'test_requirements.txt', session=PipSession(),\n+ )],\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test_dependencies.ini", "diff": "+[Flask-Testing]\n+dpkg_name: python-flask-testing\n+minimum_version: 0.6.2\n+rpm_name: python2-flask-testing\n+\n+[funcsigs]\n+dpkg_name: python-funcsigs\n+minimum_version: 1.0.2\n+python2_only: true\n+rpm_name: python2-funcsigs\n+version_property: __version__\n+\n+[mock]\n+dpkg_name: python-mock\n+minimum_version: 2.0.0\n+rpm_name: python2-mock\n+version_property: __version__\n+\n+[nose]\n+dpkg_name: python-nose\n+minimum_version: 1.3.7\n+rpm_name: python2-nose\n+\n+[pbr]\n+dpkg_name: python-pbr\n+minimum_version: 4.2.0\n+rpm_name: python2-pbr\n+\n+[six]\n+dpkg_name: python-six\n+minimum_version: 1.1.0\n+rpm_name: python2-six\n+version_property: __version__\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test_requirements.txt", "diff": "+Flask-Testing >= 0.6.2\n+funcsigs >= 1.0.2 ; python_version < '3.0'\n+mock >= 2.0.0\n+nose >= 1.3.7\n+pbr >= 4.2.0\n+six >= 1.1.0\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch.ini", "diff": "+[project]\n+name: timesketch\n+name_description: Timesketch\n+maintainer: Timesketch development team <timesketch-dev@googlegroups.com>\n+homepage_url: http://timesketch.org/\n+description_short: Collaborative digital forensic timeline analysis\n+description_long: Timesketch is a web based tool for collaborative forensic\n+ timeline analysis. Using sketches you and your collaborators can easily\n+ organize timelines and analyze them all at the same time. Add meaning\n+ to your raw data with rich annotations, comments, tags and stars.\n" } ]
Python
Apache License 2.0
google/timesketch
Added l2tdevtools configuration files and generated dependency files (#790)
263,093
26.04.2019 10:18:41
-7,200
1779c5a6f47073d059deef904457fddc0f31e8e8
Aggregation model
[ { "change_type": "MODIFY", "old_path": "timesketch/models/sketch.py", "new_path": "timesketch/models/sketch.py", "diff": "@@ -391,3 +391,40 @@ class Story(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\nself.content = content\nself.sketch = sketch\nself.user = user\n+\n+\n+class Aggregation(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\n+ BaseModel):\n+ \"\"\"Implements the Aggregation model.\"\"\"\n+ name = Column(Unicode(255))\n+ description = Column(UnicodeText())\n+ agg_type = Column(Unicode(255))\n+ parameters = Column(UnicodeText())\n+ chart_type = Column(Unicode(255))\n+ user_id = Column(Integer, ForeignKey('user.id'))\n+ sketch_id = Column(Integer, ForeignKey('sketch.id'))\n+ view_id = Column(Integer, ForeignKey('view.id'))\n+\n+ def __init__(self, name, description, agg_type, parameters, chart_type,\n+ user, sketch, view):\n+ \"\"\"Initialize the Story object.\n+\n+ Args:\n+ name (str): The name of the aggregation\n+ description (str): The description of the aggregation\n+ agg_type (str): The\n+\n+ user (User): The user who created this aggregation\n+ sketch (Sketch): The sketch that the aggregation is bound to\n+ view (View): Optional: The view that the aggregation is bound to\n+\n+ \"\"\"\n+ super(Aggregation, self).__init__()\n+ self.name = name\n+ self.description = description\n+ self.agg_type = agg_type\n+ self.parameters = parameters\n+ self.chart_type = chart_type\n+ self.user = user\n+ self.sketch = sketch\n+ self.view = view\n" } ]
Python
Apache License 2.0
google/timesketch
Aggregation model
263,093
29.04.2019 23:12:02
-7,200
1abec6b286a9b7877ea5f277060cb0a0bd460d32
Commit to DB after sketch creation
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -323,12 +323,12 @@ class SketchListResource(ResourceMixin, Resource):\ndescription=form.description.data,\nuser=current_user)\nsketch.status.append(sketch.Status(user=None, status='new'))\n+ db_session.add(sketch)\n+ db_session.commit()\n# Give the requesting user permissions on the new sketch.\nsketch.grant_permission(permission='read', user=current_user)\nsketch.grant_permission(permission='write', user=current_user)\nsketch.grant_permission(permission='delete', user=current_user)\n- db_session.add(sketch)\n- db_session.commit()\nreturn self.to_json(sketch, status_code=HTTP_STATUS_CODE_CREATED)\nreturn abort(HTTP_STATUS_CODE_BAD_REQUEST)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/testlib.py", "new_path": "timesketch/lib/testlib.py", "diff": "@@ -302,7 +302,7 @@ class BaseTest(TestCase):\nReturns:\nA user (instance of timesketch.models.user.User)\n\"\"\"\n- user = User(username=username)\n+ user = User.get_or_create(username=username)\nif set_password:\nuser.set_password(plaintext='test', rounds=4)\nself._commit_to_database(user)\n@@ -317,7 +317,7 @@ class BaseTest(TestCase):\nReturns:\nA group (instance of timesketch.models.user.Group)\n\"\"\"\n- group = Group(name=name)\n+ group = Group.get_or_create(name=name)\nuser.groups.append(group)\nself._commit_to_database(group)\nreturn group\n@@ -333,7 +333,7 @@ class BaseTest(TestCase):\nReturns:\nA sketch (instance of timesketch.models.sketch.Sketch)\n\"\"\"\n- sketch = Sketch(name=name, description=name, user=user)\n+ sketch = Sketch.get_or_create(name=name, description=name, user=user)\nif acl:\nfor permission in ['read', 'write', 'delete']:\nsketch.grant_permission(permission=permission, user=user)\n@@ -355,7 +355,7 @@ class BaseTest(TestCase):\nReturns:\nA searchindex (instance of timesketch.models.sketch.SearchIndex)\n\"\"\"\n- searchindex = SearchIndex(\n+ searchindex = SearchIndex.get_or_create(\nname=name, description=name, index_name=name, user=user)\nif acl:\nfor permission in ['read', 'write', 'delete']:\n@@ -375,7 +375,7 @@ class BaseTest(TestCase):\nReturns:\nAn event (instance of timesketch.models.sketch.Event)\n\"\"\"\n- event = Event(\n+ event = Event.get_or_create(\nsketch=sketch, searchindex=searchindex, document_id='test')\ncomment = event.Comment(comment='test', user=user)\nevent.comments.append(comment)\n@@ -392,7 +392,7 @@ class BaseTest(TestCase):\nReturns:\nA story (instance of timesketch.models.story.Story)\n\"\"\"\n- story = Story(title='Test', content='Test', sketch=sketch, user=user)\n+ story = Story.get_or_create(title='Test', content='Test', sketch=sketch, user=user)\nself._commit_to_database(story)\nreturn story\n" } ]
Python
Apache License 2.0
google/timesketch
Commit to DB after sketch creation
263,093
30.04.2019 08:14:14
-7,200
e8c39d130be1cc6204cb4bcbeb9a1d15fbec4885
Upgrade SQLalchemy
[ { "change_type": "MODIFY", "old_path": "requirements.txt", "new_path": "requirements.txt", "diff": "@@ -52,7 +52,7 @@ pyyaml==4.2b4\nredis==2.10.6\nrequests==2.20.1\nsix==1.12.0 # via altair, bcrypt, cryptography, flask-restful, jsonschema, pyrsistent, python-dateutil\n-sqlalchemy==1.3.0\n+sqlalchemy==1.3.2\ntoolz==0.9.0 # via altair\ntyping==3.6.6 # via altair\nurllib3==1.24.2\n" } ]
Python
Apache License 2.0
google/timesketch
Upgrade SQLalchemy
263,178
01.05.2019 09:32:08
-7,200
2e5a8dec7fbdc6e1dc260f8ee6ac8c7a13d0557d
Removed elasticsearch5-py as a dependency
[ { "change_type": "MODIFY", "old_path": "config/linux/gift_ppa_install.sh", "new_path": "config/linux/gift_ppa_install.sh", "diff": "@@ -29,7 +29,6 @@ PYTHON2_DEPENDENCIES=\"python-alembic\npython-dateutil\npython-editor\npython-elasticsearch\n- python-elasticsearch5\npython-entrypoints\npython-enum34\npython-flask\n" }, { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "# This file is generated by l2tdevtools update-dependencies.py any dependency\n# related changes should be made in dependencies.ini.\n-DPKG_PYTHON2_DEPENDENCIES=\"python-alembic python-altair python-amqp python-aniso8601 python-asn1crypto python-attr python-bcrypt python-billiard python-blinker python-bs4 python-celery python-certifi python-cffi python-chardet python-click python-configparser python-cryptography python-datasketch python-dateutil python-editor python-elasticsearch python-elasticsearch5 python-entrypoints python-enum34 python-flask python-flask-bcrypt python-flask-login python-flask-migrate python-flask-restful python-flask-script python-flask-sqlalchemy python-flask-wtf python-gunicorn python-idna python-ipaddress python-itsdangerous python-jinja2 python-jsonschema python-jwt python-kombu python-mako python-markupsafe python-neo4jrestclient python-numpy python-pandas python-parameterized python-pycparser python-pyrsistent python-redis python-requests python-six python-sqlalchemy python-toolz python-typing python-tz python-urllib3 python-vine python-werkzeug python-wtforms python-yaml\";\n+DPKG_PYTHON2_DEPENDENCIES=\"python-alembic python-altair python-amqp python-aniso8601 python-asn1crypto python-attr python-bcrypt python-billiard python-blinker python-bs4 python-celery python-certifi python-cffi python-chardet python-click python-configparser python-cryptography python-datasketch python-dateutil python-editor python-elasticsearch python-entrypoints python-enum34 python-flask python-flask-bcrypt python-flask-login python-flask-migrate python-flask-restful python-flask-script python-flask-sqlalchemy python-flask-wtf python-gunicorn python-idna python-ipaddress python-itsdangerous python-jinja2 python-jsonschema python-jwt python-kombu python-mako python-markupsafe python-neo4jrestclient python-numpy python-pandas python-parameterized python-pycparser python-pyrsistent python-redis python-requests python-six python-sqlalchemy python-toolz python-typing python-tz python-urllib3 python-vine python-werkzeug python-wtforms python-yaml\";\nDPKG_PYTHON2_TEST_DEPENDENCIES=\"python-coverage python-flask-testing python-funcsigs python-mock python-nose python-pbr\";\n-DPKG_PYTHON3_DEPENDENCIES=\"python3-alembic python3-altair python3-amqp python3-aniso8601 python3-asn1crypto python3-attr python3-bcrypt python3-billiard python3-blinker python3-bs4 python3-celery python3-certifi python3-cffi python3-chardet python3-click python3-cryptography python3-datasketch python3-dateutil python3-editor python3-elasticsearch python3-elasticsearch5 python3-entrypoints python3-flask python3-flask-bcrypt python3-flask-login python3-flask-migrate python3-flask-restful python3-flask-script python3-flask-sqlalchemy python3-flask-wtf python3-gunicorn python3-idna python3-ipaddress python3-itsdangerous python3-jinja2 python3-jsonschema python3-jwt python3-kombu python3-mako python3-markupsafe python3-neo4jrestclient python3-numpy python3-pandas python3-parameterized python3-pycparser python3-pyrsistent python3-redis python3-requests python3-six python3-sqlalchemy python3-toolz python3-tz python3-urllib3 python3-vine python3-werkzeug python3-wtforms python3-yaml\";\n+DPKG_PYTHON3_DEPENDENCIES=\"python3-alembic python3-altair python3-amqp python3-aniso8601 python3-asn1crypto python3-attr python3-bcrypt python3-billiard python3-blinker python3-bs4 python3-celery python3-certifi python3-cffi python3-chardet python3-click python3-cryptography python3-datasketch python3-dateutil python3-editor python3-elasticsearch python3-entrypoints python3-flask python3-flask-bcrypt python3-flask-login python3-flask-migrate python3-flask-restful python3-flask-script python3-flask-sqlalchemy python3-flask-wtf python3-gunicorn python3-idna python3-ipaddress python3-itsdangerous python3-jinja2 python3-jsonschema python3-jwt python3-kombu python3-mako python3-markupsafe python3-neo4jrestclient python3-numpy python3-pandas python3-parameterized python3-pycparser python3-pyrsistent python3-redis python3-requests python3-six python3-sqlalchemy python3-toolz python3-tz python3-urllib3 python3-vine python3-werkzeug python3-wtforms python3-yaml\";\nDPKG_PYTHON3_TEST_DEPENDENCIES=\"python3-flask-testing python3-mock python3-nose python3-pbr python3-setuptools\";\n" }, { "change_type": "MODIFY", "old_path": "dependencies.ini", "new_path": "dependencies.ini", "diff": "@@ -107,14 +107,6 @@ pypi_name: elasticsearch\nrpm_name: python-elasticsearch\nversion_property: __versionstr__\n-[elasticsearch5]\n-dpkg_name: python-elasticsearch5\n-l2tbinaries_name: elasticsearch5-py\n-minimum_version: 5.4.0\n-pypi_name: elasticsearch5\n-rpm_name: python-elasticsearch5\n-version_property: __versionstr__\n-\n[enum34]\ndpkg_name: python-enum34\nminimum_version: 1.1.6\n" }, { "change_type": "MODIFY", "old_path": "setup.cfg", "new_path": "setup.cfg", "diff": "@@ -11,7 +11,6 @@ requires = Mako >= 1.0.7\nPyYAML >= 3.10\nkombu >= 4.1.0\npython-elasticsearch >= 6.0\n- python-elasticsearch5 >= 5.4.0\npython2-alembic >= 0.9.5\npython2-altair >= 2.4.1\npython2-amqp >= 2.2.1\n" } ]
Python
Apache License 2.0
google/timesketch
Removed elasticsearch5-py as a dependency (#879)
263,093
03.05.2019 09:49:34
-7,200
40e47e583dc1ddbe472722b54ee791f621ccd51c
Add analysis DB model
[ { "change_type": "MODIFY", "old_path": "timesketch/models/sketch.py", "new_path": "timesketch/models/sketch.py", "diff": "@@ -430,3 +430,39 @@ class Aggregation(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\nself.user = user\nself.sketch = sketch\nself.view = view\n+\n+\n+class Analysis(LabelMixin, StatusMixin, CommentMixin, BaseModel):\n+ \"\"\"Implements the analysis model.\"\"\"\n+ name = Column(Unicode(255))\n+ description = Column(UnicodeText())\n+ analyzer = Column(Unicode(255))\n+ parameters = Column(UnicodeText())\n+ user_id = Column(Integer, ForeignKey('user.id'))\n+ sketch_id = Column(Integer, ForeignKey('sketch.id'))\n+ timeline_id = Column(Integer, ForeignKey('timeline.id'))\n+ result = Column(UnicodeText())\n+\n+ def __init__(self, name, description, analyzer, parameters, user,\n+ sketch, timeline, result=None):\n+ \"\"\"Initialize the Aggregation object.\n+\n+ Args:\n+ name (str): Name of the analysis\n+ description (str): Description of the analysis\n+ analyzer (str): Name of the analyzer\n+ parameters (str): JSON serialized dict with analyser parameters\n+ user (User): The user who created the aggregation\n+ sketch (Sketch): The sketch that the aggregation is bound to\n+ timeline (Timeline): Timeline to to run the analysis on\n+ result (str): Result report of the analysis\n+ \"\"\"\n+ super(Analysis, self).__init__()\n+ self.name = name\n+ self.description = description\n+ self.analyzer = analyzer\n+ self.parameters = parameters\n+ self.user = user\n+ self.sketch = sketch\n+ self.timeline = timeline\n+ self.result = result\n" } ]
Python
Apache License 2.0
google/timesketch
Add analysis DB model
263,093
09.05.2019 14:45:34
-7,200
7399d0bf0d394d666ab2ae00b477322efc3e1038
Don't run all analyzers all the time
[ { "change_type": "MODIFY", "old_path": "timesketch.conf", "new_path": "timesketch.conf", "diff": "@@ -144,17 +144,16 @@ NEO4J_USERNAME = 'neo4j'\nNEO4J_PASSWORD = '<NEO4J_PASSWORD>'\n#-------------------------------------------------------------------------------\n-# Auto analyzers.\n+# Analyzers\n-ENABLE_INDEX_ANALYZERS = False\n-ENABLE_SKETCH_ANALYZERS = False\n+# Which analyzers to run automatically when a timeline is imported or added to\n+# a sketch.\n+AUTO_INDEX_ANALYZERS = []\n+AUTO_SKETCH_ANALYZERS = []\n-# Configuration.\n-\n-#-------------------------------------------------------------------------------\n# Analyzers specific configuration.\n-# What data_types to calculate a similarity score fore.\n+# What data_types to calculate a similarity score for.\nSIMILARITY_DATA_TYPES = []\n# Add all domains that are relevant to your enterprise here.\n@@ -196,3 +195,5 @@ EMAIL_USER_WHITELIST = []\n# Configuration to construct URLs for resources.\nEXTERNAL_HOST_URL = 'https://localhost'\n+\n+#-------------------------------------------------------------------------------\n" }, { "change_type": "MODIFY", "old_path": "timesketch/__init__.py", "new_path": "timesketch/__init__.py", "diff": "@@ -39,7 +39,7 @@ from timesketch.views.auth import auth_views\nfrom timesketch.views.spa import spa_views\n# Set to true to use the new Vue.js based frontend.\n-USE_NEW_FRONTEND = False\n+USE_NEW_FRONTEND = True\ndef create_app(config=None):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1560,9 +1560,8 @@ class TimelineListResource(ResourceMixin, Resource):\nreturn_code = HTTP_STATUS_CODE_OK\ntimeline = Timeline.query.get(timeline_id)\n- # If enabled, run sketch analyzers when timeline is added.\n- # Import here to avoid circular imports.\n- if current_app.config.get('ENABLE_SKETCH_ANALYZERS'):\n+ # Run sketch analyzers when timeline is added. Import here to avoid\n+ # circular imports.\nfrom timesketch.lib import tasks\nsketch_analyzer_group = tasks.build_sketch_analysis_pipeline(\nsketch_id)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -307,7 +307,7 @@ class Sketch(object):\nreturn indices\n-class BaseIndexAnalyzer(object):\n+class BaseAnalyzer(object):\n\"\"\"Base class for analyzers.\nAttributes:\n@@ -445,7 +445,7 @@ class BaseIndexAnalyzer(object):\nraise NotImplementedError\n-class BaseSketchAnalyzer(BaseIndexAnalyzer):\n+class BaseSketchAnalyzer(BaseAnalyzer):\n\"\"\"Base class for sketch analyzers.\nAttributes:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/manager.py", "new_path": "timesketch/lib/analyzers/manager.py", "diff": "@@ -22,9 +22,12 @@ class AnalysisManager(object):\n_class_registry = {}\n@classmethod\n- def _build_dependencies(cls):\n+ def _build_dependencies(cls, analyzer_names):\n\"\"\"Build a dependency list of analyzers.\n+ Args:\n+ analyzer_names (list): List of analyzer names.\n+\nReturns:\nA list of sets of analyzer names. Each set represents\none dependency group.\n@@ -33,10 +36,11 @@ class AnalysisManager(object):\nKeyError: if class introduces circular dependencies.\n\"\"\"\ndependency_tree = []\n-\ndependencies = {}\n- for name, analyzer_class in iter(cls._class_registry.items()):\n- dependencies[name] = [\n+\n+ for analyzer_name in analyzer_names:\n+ analyzer_class = cls.get_analyzer(analyzer_name)\n+ dependencies[analyzer_name] = [\nx.lower() for x in analyzer_class.DEPENDENCIES]\nwhile dependencies:\n@@ -58,10 +62,10 @@ class AnalysisManager(object):\n# Let's remove the entries already in the tree and start again.\nnew_dependencies = {}\n- for name, analyzer_dependencies in dependencies.items():\n+ for analyzer_name, analyzer_dependencies in dependencies.items():\nif not analyzer_dependencies:\ncontinue\n- new_dependencies[name] = list(\n+ new_dependencies[analyzer_name] = list(\nset(analyzer_dependencies) - dependency_set)\ndependencies = new_dependencies\n@@ -74,15 +78,22 @@ class AnalysisManager(object):\ncls._class_registry = {}\n@classmethod\n- def get_analyzers(cls):\n+ def get_analyzers(cls, analyzer_names=None):\n\"\"\"Retrieves the registered analyzers.\n+ Args:\n+ analyzer_names (list): List of analyzer names.\n+\nYields:\ntuple: containing:\nstr: the uniquely identifying name of the analyzer\ntype: the analyzer class.\n\"\"\"\n- for cluster in cls._build_dependencies():\n+ # Get all analyzers if no specific ones have been requested.\n+ if not analyzer_names:\n+ analyzer_names = cls._class_registry.keys()\n+\n+ for cluster in cls._build_dependencies(analyzer_names):\nfor analyzer_name in cluster:\nanalyzer_class = cls.get_analyzer(analyzer_name)\nyield analyzer_name, analyzer_class\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/similarity_scorer.py", "new_path": "timesketch/lib/analyzers/similarity_scorer.py", "diff": "@@ -81,7 +81,7 @@ class SimilarityScorerConfig(object):\nreturn config_dict\n-class SimilarityScorer(interface.BaseIndexAnalyzer):\n+class SimilarityScorer(interface.BaseAnalyzer):\n\"\"\"Score events based on Jaccard distance.\"\"\"\nNAME = 'SimilarityScorer'\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -115,19 +115,18 @@ def _get_index_analyzers():\nNone if index analyzers are disabled in config.\n\"\"\"\ntasks = []\n+ index_analyzers = current_app.config.get('AUTO_INDEX_ANALYZERS')\n- # Exit early if index analyzers are disabled.\n- if not current_app.config.get('ENABLE_INDEX_ANALYZERS'):\n+ if not index_analyzers:\nreturn None\n- for analyzer_name, analyzer_cls in manager.AnalysisManager.get_analyzers():\n+ for analyzer_name, analyzer_cls in manager.AnalysisManager.get_analyzers(\n+ index_analyzers):\nkwarg_list = analyzer_cls.get_kwargs()\n- if not analyzer_cls.IS_SKETCH_ANALYZER:\nif kwarg_list:\nfor kwargs in kwarg_list:\n- tasks.append(\n- run_index_analyzer.s(analyzer_name, **kwargs))\n+ tasks.append(run_index_analyzer.s(analyzer_name, **kwargs))\nelse:\ntasks.append(run_index_analyzer.s(analyzer_name))\n@@ -153,7 +152,7 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nindex_analyzer_chain = _get_index_analyzers()\nsketch_analyzer_chain = None\n- if sketch_id and current_app.config.get('ENABLE_SKETCH_ANALYZERS'):\n+ if sketch_id:\nsketch_analyzer_chain = build_sketch_analysis_pipeline(sketch_id)\nindex_task = index_task_class.s(\n@@ -181,22 +180,28 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nreturn chain(index_task, index_analyzer_chain)\n-def build_sketch_analysis_pipeline(sketch_id):\n+def build_sketch_analysis_pipeline(sketch_id, analyzer_names=None):\n\"\"\"Build a pipeline for sketch analysis.\nArgs:\n- sketch_id: The ID of the sketch to analyze.\n+ sketch_id (int): The ID of the sketch to analyze.\n+ analyzer_names (list): List of analyzers to run.\nReturns:\nCelery group with analysis tasks or None if no analyzers are enabled.\n\"\"\"\ntasks = []\n+ auto_analyzers = current_app.config.get('AUTO_SKETCH_ANALYZERS', None)\n- # Exit early if sketch analyzers are disabled.\n- if not current_app.config.get('ENABLE_SKETCH_ANALYZERS', False):\n+ # Exit early if no sketch analyzers are configured to run.\n+ if not (analyzer_names or auto_analyzers):\nreturn None\n- for analyzer_name, analyzer_cls in manager.AnalysisManager.get_analyzers():\n+ if not analyzer_names:\n+ analyzer_names = auto_analyzers\n+\n+ analyzers = manager.AnalysisManager.get_analyzers(analyzer_names)\n+ for analyzer_name, analyzer_cls in analyzers:\nkwarg_list = analyzer_cls.get_kwargs()\nif not analyzer_cls.IS_SKETCH_ANALYZER:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/testlib.py", "new_path": "timesketch/lib/testlib.py", "diff": "@@ -47,8 +47,8 @@ class TestConfig(object):\nELASTIC_PORT = None\nUPLOAD_ENABLED = False\nGRAPH_BACKEND_ENABLED = False\n- ENABLE_INDEX_ANALYZERS = False\n- ENABLE_SKETCH_ANALYZERS = False\n+ AUTO_INDEX_ANALYZERS = []\n+ AUTO_SKETCH_ANALYZERS = []\nSIMILARITY_DATA_TYPES = []\n" }, { "change_type": "MODIFY", "old_path": "timesketch/models/sketch.py", "new_path": "timesketch/models/sketch.py", "diff": "@@ -466,3 +466,24 @@ class Analysis(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nself.sketch = sketch\nself.timeline = timeline\nself.result = result\n+\n+ @property\n+ def task_id(self):\n+ \"\"\"Celery task ID.\n+\n+ Returns:\n+ Celery task ID created from index name and timeline ID.\n+ \"\"\"\n+ return '{0:s}-{1:d}'.format(\n+ self.timeline.searchindex.index_name, self.timeline.id)\n+\n+ def run(self):\n+ \"\"\"Run the analysis pipeline.\"\"\"\n+ # Import here to avoid circular imports.\n+ from timesketch.lib import tasks\n+ analyzer_group = tasks.build_sketch_analysis_pipeline(\n+ self.sketch.id, analyzer_names=[self.analyzer])\n+ if analyzer_group:\n+ pipeline = (tasks.run_sketch_init.s(\n+ [self.timeline.searchindex.index_name]) | analyzer_group)\n+ pipeline.apply_async(task_id=self.task_id)\n" } ]
Python
Apache License 2.0
google/timesketch
Don't run all analyzers all the time
263,133
17.05.2019 10:24:26
0
27bbc74bd3f5d996e266e20b0550868c642effd2
Minor changes to phishy.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/phishy_domains.py", "new_path": "timesketch/lib/analyzers/phishy_domains.py", "diff": "@@ -188,6 +188,9 @@ class PhishyDomainsSketchPlugin(interface.BaseSketchAnalyzer):\ntld = utils.get_tld_from_domain(domain)\ntld_counter[tld] += 1\n+ if not domain_counter:\n+ return 'No domains discovered, so no phishy domains.'\n+\nwatched_domains_list = current_app.config.get(\n'DOMAIN_ANALYZER_WATCHED_DOMAINS', [])\ndomain_threshold = current_app.config.get(\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to phishy.
263,178
24.05.2019 15:43:05
-7,200
cbae143ed1ccb189875f46dbdc0376edee7a5742
Updated Dockerfile to use Python 3 timesketch
[ { "change_type": "MODIFY", "old_path": "docker/Dockerfile", "new_path": "docker/Dockerfile", "diff": "@@ -10,9 +10,9 @@ RUN apt-get -y install apt-transport-https\\\ngit \\\nlibffi-dev \\\nlsb-release \\\n- python-dev\\\n- python-pip\\\n- python-psycopg2\n+ python3-dev \\\n+ python3-pip \\\n+ python3-psycopg2\nRUN curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -\nRUN VERSION=node_8.x && \\\n@@ -21,18 +21,18 @@ RUN VERSION=node_8.x && \\\nRUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -\nRUN echo \"deb https://dl.yarnpkg.com/debian/ stable main\" > /etc/apt/sources.list.d/yarn.list\n-# Install Plaso\n+# Install Plaso, nodejs and yarn.\nRUN apt-get -y install software-properties-common\nRUN add-apt-repository ppa:gift/stable && apt-get update\n-RUN apt-get update && apt-get -y install python-plaso plaso-tools nodejs yarn\n+RUN apt-get update && apt-get -y install plaso-tools nodejs yarn\n-# Use pip to install Timesketch\n-RUN pip install --upgrade pip\n+# Use Python 3 pip (pip3) to install Timesketch\n+RUN pip3 install --upgrade pip\nADD . /tmp/timesketch\nRUN cd /tmp/timesketch && yarn install && yarn run build\n-# Remove pyyaml from requirements.txt to avoid conflits with python-yaml ubuntu package\n+# Remove pyyaml from requirements.txt to avoid conflits with python-yaml Ubuntu package\nRUN sed -i -e '/pyyaml/d' /tmp/timesketch/requirements.txt\n-RUN pip install /tmp/timesketch/\n+RUN pip3 install /tmp/timesketch/\n# Copy the Timesketch configuration file into /etc\nRUN cp /tmp/timesketch/timesketch.conf /etc\n" } ]
Python
Apache License 2.0
google/timesketch
Updated Dockerfile to use Python 3 timesketch (#887)
263,093
28.05.2019 10:12:05
-7,200
e7659f13742c2dfd667b4c756ec1035d052612c0
Commit to DB earlier
[ { "change_type": "MODIFY", "old_path": "timesketch/views/home.py", "new_path": "timesketch/views/home.py", "diff": "@@ -55,12 +55,13 @@ def home():\ndescription=form.description.data,\nuser=current_user)\nsketch.status.append(sketch.Status(user=None, status='new'))\n+ db_session.add(sketch)\n+ db_session.commit()\n+\n# Give the requesting user permissions on the new sketch.\nsketch.grant_permission(permission='read', user=current_user)\nsketch.grant_permission(permission='write', user=current_user)\nsketch.grant_permission(permission='delete', user=current_user)\n- db_session.add(sketch)\n- db_session.commit()\nreturn redirect(url_for('sketch_views.overview', sketch_id=sketch.id))\nreturn render_template(\n" } ]
Python
Apache License 2.0
google/timesketch
Commit to DB earlier (#897)
263,093
28.05.2019 10:42:21
-7,200
3d1312aa81f4388c1a443237b8c89212d9b91e2a
Exit early if no domains
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/domain.py", "new_path": "timesketch/lib/analyzers/domain.py", "diff": "@@ -67,6 +67,10 @@ class DomainSketchPlugin(interface.BaseSketchAnalyzer):\ntld = '.'.join(domain.split('.')[-2:])\ntld_counter[tld] += 1\n+ # Exit early if there are no domains in the data set to analyze.\n+ if not domain_counter:\n+ return 'No domains to analyze.'\n+\ndomain_count_array = numpy.array(list(domain_counter.values()))\ndomain_20th_percentile = int(numpy.percentile(domain_count_array, 20))\ndomain_85th_percentile = int(numpy.percentile(domain_count_array, 85))\n" } ]
Python
Apache License 2.0
google/timesketch
Exit early if no domains (#898)
263,129
29.05.2019 16:04:38
-7,200
9674cafce7960ac493cbae1ff4e0963b43c74ab3
Yeti indicator analyzer
[ { "change_type": "MODIFY", "old_path": "timesketch.conf", "new_path": "timesketch.conf", "diff": "@@ -178,6 +178,16 @@ DOMAIN_ANALYZER_WATCHED_DOMAINS_SCORE_THRESHOLD = 0.75\nDOMAIN_ANALYZER_WHITELISTED_DOMAINS = ['ytimg.com', 'gstatic.com', 'yimg.com', 'akamaized.net', 'akamaihd.net', 's-microsoft.com', 'images-amazon.com', 'ssl-images-amazon.com', 'wikimedia.org', 'redditmedia.com', 'googleusercontent.com', 'googleapis.com', 'wikipedia.org', 'github.io', 'github.com']\n+# Threatintel analyzer-specific configuration\n+# URI root to Yeti's API, e.g. 'https://localhost:8080/api'\n+YETI_API_ROOT = ''\n+\n+# API key to authenticate requests\n+YETI_API_KEY = ''\n+\n+# Labels to narrow down indicator selection\n+YETI_INDICATOR_LABELS = ['domain']\n+\n#-------------------------------------------------------------------------------\n# Enable experimental UI features.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/__init__.py", "new_path": "timesketch/lib/analyzers/__init__.py", "diff": "@@ -22,3 +22,4 @@ from timesketch.lib.analyzers import feature_extraction\nfrom timesketch.lib.analyzers import login\nfrom timesketch.lib.analyzers import phishy_domains\nfrom timesketch.lib.analyzers import similarity_scorer\n+from timesketch.lib.analyzers import yetiindicators\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/yetiindicators.py", "diff": "+\"\"\"Index analyzer plugin for threatintel.\"\"\"\n+from __future__ import unicode_literals\n+\n+from flask import current_app\n+import requests\n+\n+from timesketch.lib.analyzers import interface\n+from timesketch.lib.analyzers import manager\n+from timesketch.lib import emojis\n+\n+\n+def build_query_for_indicators(indicators):\n+ \"\"\"Builds an ElasticSearch query for Yeti indicator patterns.\n+\n+ Prepends and appends .* to the regex to be able to search within a field.\n+\n+ Returns:\n+ The resulting ES query string.\n+ \"\"\"\n+ query = []\n+ for domain in indicators:\n+ query.append('domain:/.*{0:s}.*/'.format(domain['pattern']))\n+ return ' OR '.join(query)\n+\n+\n+class YetiIndicators(interface.BaseSketchAnalyzer):\n+ \"\"\"Index analyzer for Yeti threat intel indicators.\"\"\"\n+\n+ NAME = 'yetiindicators'\n+ DEPENDENCIES = frozenset(['domain'])\n+\n+ def __init__(self, index_name, sketch_id):\n+ \"\"\"Initialize the Index Analyzer.\n+\n+ Args:\n+ index_name: Elasticsearch index name\n+ \"\"\"\n+ super(YetiIndicators, self).__init__(index_name, sketch_id)\n+ self.intel = {}\n+ self.yeti_api_root = current_app.config.get('YETI_API_ROOT')\n+ self.yeti_api_key = current_app.config.get('YETI_API_KEY')\n+ self.yeti_indicator_labels = current_app.config.get(\n+ 'YETI_INDICATOR_LABELS', [])\n+\n+ def get_bad_domain_indicators(self, entity_id):\n+ \"\"\"Retrieves a list of indicators associated to a given entity.\n+\n+ Args:\n+ entity_id (str): STIX ID of the entity to get associated inticators\n+ from. (typically an Intrusion Set)\n+\n+ Returns:\n+ A list of JSON objects describing a Yeti Indicator.\n+ \"\"\"\n+ results = requests.post(\n+ self.yeti_api_root + '/entities/{0:s}/neighbors/'.format(entity_id),\n+ headers={'X-Yeti-API': self.yeti_api_key},\n+ )\n+ if results.status_code != 200:\n+ return []\n+ domain_indicators = []\n+ for neighbor in results.json().get('vertices', {}).values():\n+ if neighbor['type'] == 'x-regex' and \\\n+ set(self.yeti_indicator_labels) <= set(neighbor['labels']):\n+ domain_indicators.append(neighbor)\n+\n+ return domain_indicators\n+\n+ def get_intrusion_sets(self):\n+ \"\"\"Populates the intel attribute with data from Yeti.\n+\n+ Retrieved intel consists of Intrusion sets and associated Indicators.\n+ \"\"\"\n+ search_query = {'name': '', 'type': 'intrusion-set'}\n+ results = requests.post(\n+ self.yeti_api_root + '/entities/filter/',\n+ json={'name': '', 'type': 'intrusion-set'},\n+ headers={'X-Yeti-API': self.yeti_api_key},\n+ )\n+ if results.status_code != 200:\n+ return\n+ self.intel = {item['id']: item for item in results.json()}\n+ for _id in self.intel:\n+ self.intel[_id]['indicators'] = self.get_bad_domain_indicators(_id)\n+\n+ def run(self):\n+ \"\"\"Entry point for the analyzer.\n+\n+ Returns:\n+ String with summary of the analyzer result\n+ \"\"\"\n+\n+ self.get_intrusion_sets()\n+ actors_found = []\n+ for intrusion_set in self.intel.values():\n+ if not intrusion_set['indicators']:\n+ continue\n+\n+ found = False\n+\n+ for indicator in intrusion_set['indicators']:\n+ query = build_query_for_indicators([indicator])\n+\n+ events = self.event_stream(query_string=query,\n+ return_fields=[])\n+\n+ name = intrusion_set['name']\n+ for event in events:\n+ found = True\n+ event.add_emojis([emojis.get_emoji('SKULL')])\n+ event.add_tags([name])\n+ event.commit()\n+ event.add_comment(\n+ 'Indicator \"{0:s}\" found for actor \"{1:s}\"'.format(\n+ indicator['name'], name))\n+\n+ if found:\n+ actors_found.append(name)\n+ self.sketch.add_view(\n+ 'Domain activity for actor {0:s}'.format(name),\n+ self.NAME,\n+ query_string=query)\n+\n+ if actors_found:\n+ return '{0:d} actors were found! [{1:s}]'.format(\n+ len(actors_found), ', '.join(actors_found))\n+ return 'No indicators were found in the timeline.'\n+\n+\n+manager.AnalysisManager.register_analyzer(YetiIndicators)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/yetiindicators_test.py", "diff": "+\"\"\"Tests for ThreatintelPlugin.\"\"\"\n+from __future__ import unicode_literals\n+\n+import mock\n+\n+from timesketch.lib.analyzers import yetiindicators\n+from timesketch.lib.testlib import BaseTest\n+from timesketch.lib.testlib import MockDataStore\n+\n+MOCK_YETI_INDICATORS = [{\n+ \"created\": \"2019-05-28T15:48:12.642Z\",\n+ \"id\": \"x-regex--6ebc9344-0000-4d65-8bdd-b6dddf613068\",\n+ \"labels\": [\"domain\"],\n+ \"modified\": \"2019-05-29T11:08:01.290Z\",\n+ \"name\": \"Obvious Fancy Bear c2\",\n+ \"pattern\": \"help.notphishy.com\",\n+ \"type\": \"x-regex\",\n+ \"valid_from\": \"2019-05-01T15:47:00Z\"\n+}, {\n+ \"created\": \"2019-05-28T15:48:12.642Z\",\n+ \"id\": \"x-regex--6ebc9344-1111-4d65-8bdd-b6dddf613068\",\n+ \"labels\": [\"domain\"],\n+ \"modified\": \"2019-05-29T11:08:01.290Z\",\n+ \"name\": \"Secret Fancy Bear c2\",\n+ \"pattern\": \"help.verylegit(.com|.net)\",\n+ \"type\": \"x-regex\",\n+ \"valid_from\": \"2019-05-01T15:47:00Z\"\n+}]\n+\n+\n+class TestThreatintelPlugin(BaseTest):\n+ \"\"\"Tests the functionality of the analyzer.\"\"\"\n+\n+ def __init__(self, *args, **kwargs):\n+ super(TestThreatintelPlugin, self).__init__(*args, **kwargs)\n+\n+ # Mock the Elasticsearch datastore.\n+ @mock.patch('timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore)\n+ def test_build_query_for_indicators(self):\n+ \"\"\"Test that ES queries for indicators are correctly built.\"\"\"\n+ query = yetiindicators.build_query_for_indicators(MOCK_YETI_INDICATORS)\n+ # pylint: ignore=line-too-long\n+ self.assertEqual(\n+ query,\n+ 'domain:/.*help.notphishy.com.*/ OR domain:/.*help.verylegit(.com|.net).*/'\n+ )\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/emojis.py", "new_path": "timesketch/lib/emojis.py", "diff": "@@ -33,6 +33,7 @@ EMOJI_MAP = {\n'MAGNIFYING_GLASS': emoji('&#x1F50E', 'Search related activity'),\n'SATELLITE': emoji('&#x1F4E1', 'Domain activity'),\n'SCREEN': emoji('&#x1F5B5', 'Screensaver activity'),\n+ 'SKULL': emoji('&#x1F480;', 'Threat intel match'),\n'SKULL_CROSSBONE': emoji('&#x2620', 'Suspicious entry'),\n'SLEEPING_FACE': emoji('&#x1F634', 'Activity outside of regular hours'),\n'UNLOCK': emoji('&#x1F513', 'Logoff activity'),\n" } ]
Python
Apache License 2.0
google/timesketch
Yeti indicator analyzer
263,095
31.05.2019 13:58:16
-7,200
ade812bfba9aa8809c50ee43e9bf2908cfb2fd54
adress docstring for comment_event
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -464,15 +464,21 @@ class Sketch(BaseResource):\n\"\"\"\nAdds a comment to a single event.\n- :param event_id:\n- :param index:\n- :param comment_text:\n- :return: a json data of the query.\n+ Args:\n+ event_id: id of the event\n+ index: The Elasticsearch index name\n+ comment_text:\n+ Returns:\n+ a json data of the query.\n\"\"\"\n- form_data = {\"annotation\": comment_text,\n- \"annotation_type\": \"comment\",\n- \"events\": {\"_id\": event_id, \"_index\": index,\n- \"_type\": \"generic_event\"}}\n+ form_data = {\n+ u'annotation': comment_text,\n+ u'annotation_type': 'comment',\n+ u'events': {\n+ '_id': event_id,\n+ '_index': index,\n+ '_type': 'generic_event'}\n+ }\nresource_url = u'{0:s}/sketches/{1:d}/event/annotate/'.format(\nself.api.api_root, self.id)\nresponse = self.api.session.post(resource_url, json=form_data)\n@@ -661,8 +667,8 @@ class Timeline(BaseResource):\ntimeline_id: The primary key ID of the timeline.\nsketch_id: ID of a sketch.\napi: Instance of a TimesketchApi object.\n- name: Name of the timeline (optional)\n- searchindex: The Elasticsearch index name (optional)\n+ name: Name of the timelne (optional)\n+ searchindex: The Elasticsearch index name (optional)i\n\"\"\"\nself.id = timeline_id\nself._name = name\n" } ]
Python
Apache License 2.0
google/timesketch
adress docstring for comment_event
263,095
31.05.2019 13:59:26
-7,200
a3eb3a49a765d45ebceffcfe86cb9f2ff4665a75
label_event docstring
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -467,7 +467,7 @@ class Sketch(BaseResource):\nArgs:\nevent_id: id of the event\nindex: The Elasticsearch index name\n- comment_text:\n+ comment_text: text to add as a comment\nReturns:\na json data of the query.\n\"\"\"\n@@ -488,10 +488,12 @@ class Sketch(BaseResource):\n\"\"\"\nAdds a comment to a single event.\n- :param event_id:\n- :param index:\n- :param label_text:\n- :return: a json data of the query.\n+ Args:\n+ event_id: id of the event\n+ index: The Elasticsearch index name\n+ label_text: text used as a label\n+ Returns:\n+ a json data of the query.\n\"\"\"\nform_data = {\"annotation\": label_text,\n\"annotation_type\": \"label\",\n" } ]
Python
Apache License 2.0
google/timesketch
label_event docstring
263,093
31.05.2019 15:54:42
-7,200
5a528f2be020577dcb96dc2c6d8c8d845a4c7f94
Refactor docker directory
[ { "change_type": "MODIFY", "old_path": "docker/README.md", "new_path": "docker/README.md", "diff": "@@ -43,44 +43,6 @@ The timesketch docker config is set to write all data to the host filesystem, no\nThese locations on the host filesystem can be backed with any storage mechanism to persist sketch data beyond the container lifetimes.\n-## Development\n-\n-You can run Timesketch on Docker in development mode. To start a developer server:\n-\n-### Start a developer version of docker containers\n-\n-```\n-$ docker-compose -f timesketch-dev-compose.yml up -d\n-```\n-\n-### Find out container ID for the timesketch container\n-\n-```\n-$ docker ps\n-```\n-In the output look for CONTAINER ID for the timesketch container\n-\n-### Start a timesketch container shell\n-\n-```\n-$ docker exec -it <container ID> /bin/bash\n-```\n-### Start a celery container shell\n-\n-```\n-celery -A timesketch.lib.tasks worker --loglevel info\n-```\n-\n-### In the timesketch shell command prompt run\n-\n-```\n-tsctl runserver -h 0.0.0.0\n-```\n-\n-You now can access your development version at http://127.0.0.1:5000/\n-Log in with user: dev password: dev\n-\n-\n" }, { "change_type": "RENAME", "old_path": "docker/Dockerfile-dev", "new_path": "docker/development/Dockerfile", "diff": "-# Use the official Docker Hub Ubuntu 14.04 base image\n-FROM ubuntu:18.04\n+# Use the latest Timesketch development base image\n+FROM timesketch/timesketch-dev-base:latest\n# Copy the entrypoint script into the container\n-COPY docker/timesketch-dev-entrypoint.sh /docker-entrypoint.sh\n+COPY docker/development/docker-entrypoint.sh /docker-entrypoint.sh\nRUN chmod a+x /docker-entrypoint.sh\n# Load the entrypoint script to be run later\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docker/development/README.md", "diff": "+## Development\n+\n+You can run Timesketch on Docker in development mode.\n+\n+### Start a developer version of docker containers in this directory\n+\n+```\n+$ docker-compose up -d\n+```\n+\n+### Find out container ID for the timesketch container\n+\n+```\n+$ CONTAINER_ID=\"$(sudo docker container list -f name=docker_timesketch -q)\"\n+```\n+In the output look for CONTAINER ID for the timesketch container\n+\n+### Start a celery container shell\n+```\n+$ sudo docker exec -it $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n+```\n+\n+### Start development webserver\n+\n+```\n+sudo docker exec -it $CONTAINER_ID gunicorn --reload -b 0.0.0.0:5000 --log-file - --timeout 120 timesketch.wsgi:application\n+```\n+\n+You now can access your development version at http://127.0.0.1:5000/\n+Log in with user: dev password: dev\n+\n" }, { "change_type": "RENAME", "old_path": "docker/timesketch-dev-compose.yml", "new_path": "docker/development/docker-compose.yml", "diff": "@@ -3,7 +3,7 @@ services:\ntimesketch:\nbuild:\ncontext: ../\n- dockerfile: ./docker/Dockerfile-dev\n+ dockerfile: ./docker/development/Dockerfile\nports:\n- \"127.0.0.1:5000:5000\"\nlinks:\n@@ -26,7 +26,7 @@ services:\n- CHOKIDAR_USEPOLLING=true\nrestart: always\nvolumes:\n- - ../:/usr/local/src/timesketch/\n+ - ../../:/usr/local/src/timesketch/\nelasticsearch:\nimage: elasticsearch:6.4.2\n" }, { "change_type": "RENAME", "old_path": "docker/timesketch-dev-entrypoint.sh", "new_path": "docker/development/docker-entrypoint.sh", "diff": "# Run the container the default way\nif [ \"$1\" = 'timesketch' ]; then\n- # Update the base image\n- apt-get update && apt-get -y upgrade\n-\n- # Setup install environment and Timesketch dependencies\n- apt-get -y install apt-transport-https\\\n- curl\\\n- git\\\n- libffi-dev\\\n- lsb-release\\\n- python-dev\\\n- python-pip\\\n- python-psycopg2\n-\n- curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -\n- VERSION=node_8.x\n- DISTRO=\"$(lsb_release -s -c)\"\n- echo \"deb https://deb.nodesource.com/$VERSION $DISTRO main\" > /etc/apt/sources.list.d/nodesource.list\n- curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -\n- echo \"deb https://dl.yarnpkg.com/debian/ stable main\" > /etc/apt/sources.list.d/yarn.list\n-\n- # Install Plaso and Yarn\n- apt-get -y install software-properties-common\n- add-apt-repository ppa:gift/stable && apt-get update\n- apt-get update && apt-get -y install python-plaso plaso-tools nodejs yarn\n-\n# Install Timesketch from volume\ncd /usr/local/src/timesketch && yarn install && yarn run build\npip install -e /usr/local/src/timesketch/\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docker/factory/development/Dockerfile", "diff": "+# Use the official Docker Hub Ubuntu 18.04 base image\n+FROM ubuntu:18.04\n+\n+RUN apt-get -y update\n+RUN apt-get -y upgrade\n+RUN apt-get -y install software-properties-common apt-transport-https apt-utils curl git python3-dev python3-pip python3-psycopg2\n+\n+# Install Plaso\n+RUN add-apt-repository -y ppa:gift/stable\n+RUN apt-get -y update\n+RUN apt-get -y install python-plaso plaso-tools\n+RUN apt-get clean && rm -rf /var/cache/apt/* /var/lib/apt/lists/*\n+\n+# Install NodeJS and Yarn to build the frontend\n+RUN curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -\n+RUN VERSION=node_8.x && \\\n+ DISTRO=\"$(lsb_release -s -c)\" && \\\n+ echo \"deb https://deb.nodesource.com/$VERSION $DISTRO main\" > /etc/apt/sources.list.d/nodesource.list\n+RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -\n+RUN echo \"deb https://dl.yarnpkg.com/debian/ stable main\" > /etc/apt/sources.list.d/yarn.list\n+RUN apt-get update\n+RUN apt-get -y install nodejs yarn\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
Refactor docker directory
263,143
05.06.2019 14:24:28
0
e3adf437624b35a7653263846e0076f030acafd2
initial gcp servicekey usage analyzer
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/__init__.py", "new_path": "timesketch/lib/analyzers/__init__.py", "diff": "@@ -22,3 +22,4 @@ from timesketch.lib.analyzers import feature_extraction\nfrom timesketch.lib.analyzers import login\nfrom timesketch.lib.analyzers import phishy_domains\nfrom timesketch.lib.analyzers import similarity_scorer\n+from timesketch.lib.analyzers import gcp_servicekey\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/gcp_servicekey.py", "diff": "+\"\"\"Sketch analyzer plugin for GCP Service Key usage.\"\"\"\n+from __future__ import unicode_literals\n+\n+from timesketch.lib import emojis\n+from timesketch.lib.analyzers import interface\n+from timesketch.lib.analyzers import manager\n+\n+\n+class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\n+ \"\"\"Sketch analyzer for GCP Service Key usage.\"\"\"\n+\n+ NAME = 'gcp_servicekey'\n+\n+ def __init__(self, index_name, sketch_id):\n+ \"\"\"Initialize The Sketch Analyzer.\n+\n+ Args:\n+ index_name: Elasticsearch index name\n+ sketch_id: Sketch ID\n+ \"\"\"\n+ self.index_name = index_name\n+ super(GcpServiceKeySketchPlugin, self).__init__(index_name, sketch_id)\n+\n+ def run(self):\n+ \"\"\"Entry point for the analyzer.\n+\n+ Returns:\n+ String with summary of the analyzer result\n+ \"\"\"\n+ query = ('event_subtype:compute.instances.insert AND user:*gserviceaccount*')\n+ return_fields = ['message', 'event_subtype', 'event_type', 'user', 'name']\n+\n+ # Generator of events based on your query.\n+ events = self.event_stream(\n+ query_string=query, return_fields=return_fields)\n+\n+ gcp_servicekey_counter = 0\n+\n+ for event in events:\n+ # Fields to analyze.\n+ message = event.source.get('message')\n+ event_subtype = event.source.get('event_subtype')\n+ event_type = event.source.get('event_type')\n+ user = event.source.get('user')\n+ name = event.source.get('name')\n+\n+ if event_type == 'GCE_OPERATION_DONE':\n+ event.add_star()\n+ event.add_tags('GCP Success Event')\n+ event.add_label('vm_created')\n+\n+ # Commit the event to the datastore.\n+ event.commit()\n+ gcp_servicekey_counter += 1\n+\n+ # Create a saved view with our query.\n+ if gcp_servicekey_counter:\n+ self.sketch.add_view('GCP ServiceKey activity', 'gcp_servicekey', query_string=query)\n+\n+ # TODO: Return a summary from the analyzer.\n+ return 'GCP ServiceKey analyzer completed, {0:d} service key marked'.format(gcp_servicekey_counter)\n+\n+\n+manager.AnalysisManager.register_analyzer(GcpServiceKeySketchPlugin)\n" } ]
Python
Apache License 2.0
google/timesketch
initial gcp servicekey usage analyzer
263,093
12.06.2019 09:25:31
-7,200
99b1ac8cc94923c10799a78620c5279b941cb870
Kwargs for analyzers
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1674,11 +1674,11 @@ class TimelineListResource(ResourceMixin, Resource):\n# circular imports.\nfrom timesketch.lib import tasks\nsketch_analyzer_group = tasks.build_sketch_analysis_pipeline(\n- sketch_id)\n+ sketch_id, searchindex_id, current_user.id)\nif sketch_analyzer_group:\npipeline = (tasks.run_sketch_init.s(\n[searchindex.index_name]) | sketch_analyzer_group)\n- pipeline.apply_async(task_id=searchindex.index_name)\n+ pipeline.apply_async()\nreturn self.to_json(\ntimeline, meta=metadata, status_code=return_code)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -29,6 +29,7 @@ from timesketch.models.sketch import Event as SQLEvent\nfrom timesketch.models.sketch import Sketch as SQLSketch\nfrom timesketch.models.sketch import SearchIndex\nfrom timesketch.models.sketch import View\n+from timesketch.models.sketch import Analysis\ndef _flush_datastore_decorator(func):\n@@ -307,7 +308,7 @@ class Sketch(object):\nreturn indices\n-class BaseAnalyzer(object):\n+class BaseIndexAnalyzer(object):\n\"\"\"Base class for analyzers.\nAttributes:\n@@ -391,7 +392,7 @@ class BaseAnalyzer(object):\nyield Event(event, self.datastore, sketch=self.sketch)\n@_flush_datastore_decorator\n- def run_wrapper(self):\n+ def run_wrapper(self, analysis_id):\n\"\"\"A wrapper method to run the analyzer.\nThis method is decorated to flush the bulk insert operation on the\n@@ -400,52 +401,26 @@ class BaseAnalyzer(object):\nReturns:\nReturn value of the run method.\n\"\"\"\n- result = self.run()\n-\n- # Update the searchindex description with analyzer result.\n- # TODO: Don't overload the description field.\n- searchindex = SearchIndex.query.filter_by(\n- index_name=self.index_name).first()\n+ analysis = Analysis.query.get(analysis_id)\n+ analysis.set_status('STARTED')\n- # Some code paths set the description equals to the name. Remove that\n- # here to get a clean description with only analyzer results.\n- if searchindex.description == searchindex.name:\n- searchindex.description = ''\n+ # Run the analyzer\n+ result = self.run()\n- # Append the analyzer result.\n- if result:\n- searchindex.description = '{0:s}\\n{1:s}'.format(\n- searchindex.description, result)\n- db_session.add(searchindex)\n+ # Update database analysis object with result and status\n+ analysis.result = '{0:s}'.format(result)\n+ analysis.set_status('DONE')\n+ db_session.add(analysis)\ndb_session.commit()\nreturn result\n- @classmethod\n- def get_kwargs(cls):\n- \"\"\"Get keyword arguments needed to instantiate the class.\n-\n- Every analyzer gets the index_name as its first argument from Celery.\n- By default this is the only argument. If your analyzer need more\n- arguments you can override this method and return as a dictionary.\n-\n- If you want more than one instance to be created for your analyzer you\n- can return a list of dictionaries with kwargs and each one will be\n- instantiated and registered in Celery. This is neat if you want to run\n- your analyzer with different arguments in parallel.\n-\n- Returns:\n- List of keyword argument dicts or None if no extra arguments are\n- needed.\n- \"\"\"\n- return None\n-\ndef run(self):\n\"\"\"Entry point for the analyzer.\"\"\"\nraise NotImplementedError\n-class BaseSketchAnalyzer(BaseAnalyzer):\n+class BaseSketchAnalyzer(BaseIndexAnalyzer):\n\"\"\"Base class for sketch analyzers.\nAttributes:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/similarity_scorer.py", "new_path": "timesketch/lib/analyzers/similarity_scorer.py", "diff": "@@ -81,48 +81,22 @@ class SimilarityScorerConfig(object):\nreturn config_dict\n-class SimilarityScorer(interface.BaseAnalyzer):\n+class SimilarityScorer(interface.BaseSketchAnalyzer):\n\"\"\"Score events based on Jaccard distance.\"\"\"\n- NAME = 'SimilarityScorer'\n+ NAME = 'similarity_scorer'\nDEPENDENCIES = frozenset()\n- def __init__(self, index_name, data_type=None):\n+ def __init__(self, index_name, sketch_id, data_type):\n\"\"\"Initializes a similarity scorer.\nArgs:\nindex_name: Elasticsearch index name.\ndata_type: Name of the data_type.\n\"\"\"\n- if data_type:\nself._config = SimilarityScorerConfig(index_name, data_type)\n- else:\n- self._config = None\n- super(SimilarityScorer, self).__init__(index_name)\n-\n- @classmethod\n- def get_kwargs(cls):\n- \"\"\"Keyword arguments needed to instantiate the class.\n-\n- In addition to the index_name passed to the constructor by default we\n- need the data_type name as well. Furthermore we want to instantiate\n- one task per data_type in order to run the analyzer in parallel. To\n- achieve this we override this method and return a list of keyword\n- argument dictionaries.\n-\n- Returns:\n- List of keyword arguments (dict), one per data_type.\n- \"\"\"\n- kwargs_list = []\n- try:\n- data_types = current_app.config['SIMILARITY_DATA_TYPES']\n- if data_types:\n- for data_type in data_types:\n- kwargs_list.append({'data_type': data_type})\n- except KeyError:\n- return None\n- return kwargs_list\n+ super(SimilarityScorer, self).__init__(index_name, sketch_id)\ndef run(self):\n\"\"\"Entry point for the SimilarityScorer.\n@@ -131,10 +105,6 @@ class SimilarityScorer(interface.BaseAnalyzer):\nA dict with metadata about the processed data set or None if no\ndata_types has been configured.\n\"\"\"\n- # Exit early if there is no data_type to process.\n- if not self._config:\n- return None\n-\n# Event generator for streaming results.\nevents = self.event_stream(\nquery_string=self._config.query,\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -19,6 +19,7 @@ import logging\nimport subprocess\nimport traceback\n+import json\nimport six\nfrom celery import chain\n@@ -36,6 +37,9 @@ from timesketch.models import db_session\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\n+from timesketch.models.user import User\ncelery = create_celery_app()\n@@ -153,7 +157,8 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nsketch_analyzer_chain = None\nif sketch_id:\n- sketch_analyzer_chain = build_sketch_analysis_pipeline(sketch_id)\n+ sketch_analyzer_chain = build_sketch_analysis_pipeline(\n+ sketch_id, user_id=None)\nindex_task = index_task_class.s(\nfile_path, timeline_name, index_name, file_extension)\n@@ -180,12 +185,16 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nreturn chain(index_task, index_analyzer_chain)\n-def build_sketch_analysis_pipeline(sketch_id, analyzer_names=None):\n+def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\n+ analyzer_names=None, analyzer_kwargs=None):\n\"\"\"Build a pipeline for sketch analysis.\nArgs:\nsketch_id (int): The ID of the sketch to analyze.\n+ searchindex_id (int): The ID of the searchhindex to analyze.\n+ user_id (int): The ID of the user who started the analyzer.\nanalyzer_names (list): List of analyzers to run.\n+ analyzer_kwargs (dict): Arguments to the analyzer.\nReturns:\nCelery group with analysis tasks or None if no analyzers are enabled.\n@@ -200,23 +209,46 @@ def build_sketch_analysis_pipeline(sketch_id, analyzer_names=None):\nif not analyzer_names:\nanalyzer_names = auto_analyzers\n+ user = User.query.get(user_id)\n+ sketch = Sketch.query.get(sketch_id)\n+ analysis_session = AnalysisSession(user, sketch)\n+\nanalyzers = manager.AnalysisManager.get_analyzers(analyzer_names)\nfor analyzer_name, analyzer_cls in analyzers:\n- kwarg_list = analyzer_cls.get_kwargs()\n-\nif not analyzer_cls.IS_SKETCH_ANALYZER:\ncontinue\n- if kwarg_list:\n- for kwargs in kwarg_list:\n- tasks.append(run_sketch_analyzer.s(\n- sketch_id, analyzer_name, **kwargs))\n+ if analyzer_kwargs:\n+ kwargs = analyzer_kwargs.get(analyzer_name, {})\nelse:\n- tasks.append(run_sketch_analyzer.s(sketch_id, analyzer_name))\n+ kwargs = {}\n+\n+ searchindex = SearchIndex.query.get(searchindex_id)\n+ timeline = Timeline.query.filter_by(\n+ sketch=sketch, searchindex=searchindex).first()\n+\n+ analysis = Analysis(\n+ name=analyzer_name,\n+ description=analyzer_name,\n+ analyzer_name=analyzer_name,\n+ parameters=json.dumps(kwargs),\n+ user=user,\n+ sketch=sketch,\n+ timeline=timeline)\n+ analysis.set_status('PENDING')\n+ analysis_session.analyses.append(analysis)\n+ db_session.add(analysis)\n+ db_session.commit()\n+\n+ tasks.append(run_sketch_analyzer.s(\n+ sketch_id, analysis.id, analyzer_name, **kwargs))\nif current_app.config.get('ENABLE_EMAIL_NOTIFICATIONS'):\ntasks.append(run_email_result_task.s(sketch_id))\n+ if not tasks:\n+ return\n+\nreturn chain(tasks)\n@@ -322,12 +354,14 @@ def run_index_analyzer(index_name, analyzer_name, **kwargs):\n@celery.task(track_started=True)\n-def run_sketch_analyzer(index_name, sketch_id, analyzer_name, **kwargs):\n+def run_sketch_analyzer(index_name, sketch_id, analysis_id, analyzer_name,\n+ **kwargs):\n\"\"\"Create a Celery task for a sketch analyzer.\nArgs:\nindex_name: Name of the datastore index.\nsketch_id: ID of the sketch to analyze.\n+ analysis_id: ID of the analysis.\nanalyzer_name: Name of the analyzer.\nReturns:\n@@ -336,7 +370,8 @@ def run_sketch_analyzer(index_name, sketch_id, analyzer_name, **kwargs):\nanalyzer_class = manager.AnalysisManager.get_analyzer(analyzer_name)\nanalyzer = analyzer_class(\nsketch_id=sketch_id, index_name=index_name, **kwargs)\n- result = analyzer.run_wrapper()\n+\n+ result = analyzer.run_wrapper(analysis_id)\nlogging.info('[{0:s}] result: {1:s}'.format(analyzer_name, result))\nreturn index_name\n" }, { "change_type": "MODIFY", "old_path": "timesketch/models/sketch.py", "new_path": "timesketch/models/sketch.py", "diff": "from __future__ import unicode_literals\nimport json\n+import uuid\nfrom sqlalchemy import Column\nfrom sqlalchemy import ForeignKey\n@@ -50,6 +51,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+ analysis = relationship('Analysis', backref='sketch', lazy='select')\ndef __init__(self, name, description, user):\n\"\"\"Initialize the Sketch object.\n@@ -162,6 +164,7 @@ class Timeline(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nuser_id = Column(Integer, ForeignKey('user.id'))\nsearchindex_id = Column(Integer, ForeignKey('searchindex.id'))\nsketch_id = Column(Integer, ForeignKey('sketch.id'))\n+ analysis = relationship('Analysis', backref='timeline', lazy='select')\ndef __init__(self,\nname,\n@@ -438,54 +441,60 @@ class Analysis(LabelMixin, StatusMixin, CommentMixin, BaseModel):\n\"\"\"Implements the analysis model.\"\"\"\nname = Column(Unicode(255))\ndescription = Column(UnicodeText())\n- analyzer = Column(Unicode(255))\n+ analyzer_name = Column(Unicode(255))\nparameters = Column(UnicodeText())\n+ result = Column(UnicodeText())\n+ log = Column(UnicodeText())\n+ analysissession_id = Column(Integer, ForeignKey('analysissession.id'))\nuser_id = Column(Integer, ForeignKey('user.id'))\nsketch_id = Column(Integer, ForeignKey('sketch.id'))\ntimeline_id = Column(Integer, ForeignKey('timeline.id'))\n- result = Column(UnicodeText())\n+ searchindex_id = Column(Integer, ForeignKey('searchindex.id'))\n- def __init__(self, name, description, analyzer, parameters, user,\n- sketch, timeline, result=None):\n- \"\"\"Initialize the Aggregation object.\n+ def __init__(self, name, description, analyzer_name, parameters, user,\n+ sketch, timeline=None, searchindex=None, result=None,\n+ log=None):\n+ \"\"\"Initialize the Analysis object.\nArgs:\nname (str): Name of the analysis\ndescription (str): Description of the analysis\n- analyzer (str): Name of the analyzer\n+ analyzer_name (str): Name of the analyzer\nparameters (str): JSON serialized dict with analyser parameters\nuser (User): The user who created the aggregation\nsketch (Sketch): The sketch that the aggregation is bound to\n- timeline (Timeline): Timeline to to run the analysis on\n+ timeline (Timeline): Timeline the analysis was run on\n+ searchindex (SearchIndex): SearchIndex the analysis was run on\nresult (str): Result report of the analysis\n+ log (str): Log of the analysis\n\"\"\"\nsuper(Analysis, self).__init__()\nself.name = name\nself.description = description\n- self.analyzer = analyzer\n+ self.analyzer_name = analyzer_name\nself.parameters = parameters\nself.user = user\nself.sketch = sketch\nself.timeline = timeline\n+ self.searchindex = searchindex\nself.result = result\n+ self.log = log\n- @property\n- def task_id(self):\n- \"\"\"Celery task ID.\n- Returns:\n- Celery task ID created from index name and timeline ID.\n+class AnalysisSession(LabelMixin, StatusMixin, CommentMixin, BaseModel):\n+ \"\"\"Implements the analysis session model.\"\"\"\n+ user_id = Column(Integer, ForeignKey('user.id'))\n+ sketch_id = Column(Integer, ForeignKey('sketch.id'))\n+ analyses = relationship(\n+ 'Analysis', backref='analysissession', lazy='select')\n+\n+ def __init__(self, user, sketch):\n+ \"\"\"Initialize the AnalysisSession object.\n+\n+ Args:\n+ user (User): The user who created the aggregation\n+ sketch (Sketch): The sketch that the aggregation is bound to\n\"\"\"\n- return '{0:s}-{1:d}'.format(\n- self.timeline.searchindex.index_name, self.timeline.id)\n-\n- def run(self):\n- \"\"\"Run the analysis pipeline.\"\"\"\n- # Import here to avoid circular imports.\n- from timesketch.lib import tasks\n- analyzer_group = tasks.build_sketch_analysis_pipeline(\n- self.sketch.id, analyzer_names=[self.analyzer])\n- if analyzer_group:\n- pipeline = (tasks.run_sketch_init.s(\n- [self.timeline.searchindex.index_name]) | analyzer_group)\n- pipeline.apply_async(task_id=self.task_id)\n+ super(AnalysisSession, self).__init__()\n+ self.user = user\n+ self.sketch = sketch\n" }, { "change_type": "MODIFY", "old_path": "timesketch/views/sketch.py", "new_path": "timesketch/views/sketch.py", "diff": "@@ -378,7 +378,7 @@ def timelines(sketch_id):\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\nsketch_analyzer_group = tasks.build_sketch_analysis_pipeline(\n- sketch_id)\n+ sketch_id, current_user.id)\nif sketch_analyzer_group:\npipeline = (tasks.run_sketch_init.s(\n[searchindex.index_name]) | sketch_analyzer_group)\n" } ]
Python
Apache License 2.0
google/timesketch
Kwargs for analyzers
263,093
12.06.2019 09:43:50
-7,200
ca690d437127e913faf4474c0dbbf4174408750e
index pipeline
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1344,7 +1344,7 @@ class UploadFileResource(ResourceMixin, Resource):\nfrom timesketch.lib import tasks\npipeline = tasks.build_index_pipeline(\nfile_path, timeline_name, index_name, file_extension, sketch_id)\n- pipeline.apply_async(task_id=index_name)\n+ pipeline.apply_async()\n# Return Timeline if it was created.\n# pylint: disable=no-else-return\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -155,10 +155,11 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nindex_task_class = _get_index_task_class(file_extension)\nindex_analyzer_chain = _get_index_analyzers()\nsketch_analyzer_chain = None\n+ searchindex = SearchIndex.query.filter_by(index_name=index_name).first()\nif sketch_id:\nsketch_analyzer_chain = build_sketch_analysis_pipeline(\n- sketch_id, user_id=None)\n+ sketch_id, searchindex.id, user_id=None)\nindex_task = index_task_class.s(\nfile_path, timeline_name, index_name, file_extension)\n@@ -209,7 +210,11 @@ def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\nif not analyzer_names:\nanalyzer_names = auto_analyzers\n+ if user_id:\nuser = User.query.get(user_id)\n+ else:\n+ user = None\n+\nsketch = Sketch.query.get(sketch_id)\nanalysis_session = AnalysisSession(user, sketch)\n@@ -243,6 +248,10 @@ def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\ntasks.append(run_sketch_analyzer.s(\nsketch_id, analysis.id, analyzer_name, **kwargs))\n+ # Commit the analysis session to the database.\n+ db_session.add(analysis_session)\n+ db_session.commit()\n+\nif current_app.config.get('ENABLE_EMAIL_NOTIFICATIONS'):\ntasks.append(run_email_result_task.s(sketch_id))\n" } ]
Python
Apache License 2.0
google/timesketch
index pipeline
263,093
13.06.2019 11:49:32
-7,200
7578237511cec580507ec991c487162f378e77b8
Default kwargs in config
[ { "change_type": "MODIFY", "old_path": "data/timesketch.conf", "new_path": "data/timesketch.conf", "diff": "@@ -140,6 +140,20 @@ NEO4J_PASSWORD = '<NEO4J_PASSWORD>'\nAUTO_INDEX_ANALYZERS = []\nAUTO_SKETCH_ANALYZERS = []\n+# Optional specify any default arguments to pass to analyzers.\n+# The format is:\n+# {'analyzer1_name': {\n+ 'param1': 'value'\n+ },\n+ {'analyzer2_name': {\n+ 'param1': 'value'\n+ }\n+ }\n+ }\n+AUTO_SKETCH_ANALYZERS_KWARGS = {}\n+ANALYZERS_DEFAULT_KWARGS = {}\n+\n+\n# Add all domains that are relevant to your enterprise here.\n# All domains in this list are added to the list of watched\n# domains and compared to other domains in the timeline to\n" }, { "change_type": "MODIFY", "old_path": "docker/Dockerfile", "new_path": "docker/Dockerfile", "diff": "@@ -38,7 +38,7 @@ RUN pip3 install /tmp/timesketch/\nRUN cp /tmp/timesketch/data/timesketch.conf /etc\n# Copy Timesketch config files into /etc/timesketch\nRUN mkdir /etc/timesketch\n-RUN cp -r /tmp/timesketch/data/features.yaml /etc/timesketch/\n+RUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\n# Copy the entrypoint script into the container\nCOPY docker/docker-entrypoint.sh /\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -126,12 +126,6 @@ def _get_index_analyzers():\nfor analyzer_name, analyzer_cls in manager.AnalysisManager.get_analyzers(\nindex_analyzers):\n- kwarg_list = analyzer_cls.get_kwargs()\n-\n- if kwarg_list:\n- for kwargs in kwarg_list:\n- tasks.append(run_index_analyzer.s(analyzer_name, **kwargs))\n- else:\ntasks.append(run_index_analyzer.s(analyzer_name))\nreturn chain(tasks)\n@@ -190,6 +184,12 @@ def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\nanalyzer_names=None, analyzer_kwargs=None):\n\"\"\"Build a pipeline for sketch analysis.\n+ If no analyzer_names is passed in then we assume auto analyzers should be\n+ run and get this list from the configuration. Parameters to the analyzers\n+ can be passed in to this function, otherwise they will be taken from the\n+ configuration. Either default kwargs for auto analyzers or defaults for\n+ manually run analyzers.\n+\nArgs:\nsketch_id (int): The ID of the sketch to analyze.\nsearchindex_id (int): The ID of the searchindex to analyze.\n@@ -201,14 +201,19 @@ def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\nCelery group with analysis tasks or None if no analyzers are enabled.\n\"\"\"\ntasks = []\n- auto_analyzers = current_app.config.get('AUTO_SKETCH_ANALYZERS', None)\n+\n+ if not analyzer_names:\n+ analyzer_names = current_app.config.get('AUTO_SKETCH_ANALYZERS', [])\n+ if not analyzer_kwargs:\n+ analyzer_kwargs = current_app.config.get(\n+ 'AUTO_SKETCH_ANALYZERS_KWARGS', {})\n# Exit early if no sketch analyzers are configured to run.\n- if not (analyzer_names or auto_analyzers):\n+ if not analyzer_names:\nreturn None\n- if not analyzer_names:\n- analyzer_names = auto_analyzers\n+ if not analyzer_kwargs:\n+ analyzer_kwargs = current_app.config.get('ANALYZERS_DEFAULT_KWARGS', {})\nif user_id:\nuser = User.query.get(user_id)\n@@ -223,11 +228,7 @@ def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\nif not analyzer_cls.IS_SKETCH_ANALYZER:\ncontinue\n- if analyzer_kwargs:\nkwargs = analyzer_kwargs.get(analyzer_name, {})\n- else:\n- kwargs = {}\n-\nsearchindex = SearchIndex.query.get(searchindex_id)\ntimeline = Timeline.query.filter_by(\nsketch=sketch, searchindex=searchindex).first()\n" } ]
Python
Apache License 2.0
google/timesketch
Default kwargs in config
263,093
13.06.2019 14:05:55
-7,200
2a801b37b1829f2e7d3629cb1e04c647818ea35b
Make sketch title and desc editabe
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -396,6 +396,28 @@ class SketchResource(ResourceMixin, Resource):\nsketch.set_status(status='deleted')\nreturn HTTP_STATUS_CODE_OK\n+ @login_required\n+ def post(self, sketch_id):\n+ \"\"\"Handles POST request to the resource.\n+\n+ Returns:\n+ A sketch in JSON (instance of flask.wrappers.Response)\n+ \"\"\"\n+ form = NameDescriptionForm.build(request)\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+\n+ if not form.validate_on_submit():\n+ return abort(HTTP_STATUS_CODE_BAD_REQUEST)\n+\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN)\n+\n+ sketch.name = form.name.data\n+ sketch.description = form.description.data\n+ db_session.add(sketch)\n+ db_session.commit()\n+ return self.to_json(sketch, status_code=HTTP_STATUS_CODE_CREATED)\n+\nclass ViewListResource(ResourceMixin, Resource):\n\"\"\"Resource to create a View.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "timesketch/frontend/src/components/SketchOverviewSummary.vue", "new_path": "timesketch/frontend/src/components/SketchOverviewSummary.vue", "diff": "@@ -15,15 +15,39 @@ limitations under the License.\n-->\n<template>\n<div>\n- <h4 class=\"title is-4\">{{ sketch.name }}</h4>\n- <p>{{ sketch.description }}</p>\n+ <h4 class=\"title is-4\" :contenteditable=\"meta.permissions.write\" v-text=\"sketch.name\" @blur=\"onEditTitle\" @keydown.enter.prevent=\"onEditTitle\"></h4>\n+ <p :contenteditable=\"meta.permissions.write\" v-text=\"sketch.description\" @blur=\"onEditDescription\" @keydown.enter.prevent=\"onEditDescription\"></p>\n</div>\n</template>\n<script>\n+import ApiClient from '../utils/RestApiClient'\n+\nexport default {\nname: 'ts-sketch-overview-summary',\n- props: ['sketch']\n+ computed: {\n+ sketch () {\n+ return this.$store.state.sketch\n+ },\n+ meta () {\n+ return this.$store.state.meta\n+ }\n+ },\n+ methods: {\n+ onEditTitle (e) {\n+ this.sketch.name = e.target.innerText\n+ this.saveSketchSummary()\n+ },\n+ onEditDescription (e) {\n+ this.sketch.description = e.target.innerText\n+ this.saveSketchSummary()\n+ },\n+ saveSketchSummary () {\n+ ApiClient.saveSketchSummary(this.sketch.id, this.sketch.name, this.sketch.description).then((response) => {}).catch((e) => {\n+ console.error(e)\n+ })\n+ }\n+ }\n}\n</script>\n" }, { "change_type": "MODIFY", "old_path": "timesketch/frontend/src/utils/RestApiClient.js", "new_path": "timesketch/frontend/src/utils/RestApiClient.js", "diff": "@@ -53,6 +53,13 @@ export default {\n}\nreturn RestApiClient.post('/sketches/' + sketchId + /timelines/ + timelineId + '/', formData)\n},\n+ saveSketchSummary (sketchId, name, description) {\n+ let formData = {\n+ name: name,\n+ description: description\n+ }\n+ return RestApiClient.post('/sketches/' + sketchId + '/', formData)\n+ },\ndeleteSketchTimeline (sketchId, timelineId) {\nreturn RestApiClient.delete('/sketches/' + sketchId + /timelines/ + timelineId + '/')\n},\n" } ]
Python
Apache License 2.0
google/timesketch
Make sketch title and desc editabe
263,133
20.06.2019 12:07:41
0
6af8558a326bd148da9c5dc3c28b00b4e652fd72
Minor changes to docker configs.
[ { "change_type": "MODIFY", "old_path": "docker/Dockerfile", "new_path": "docker/Dockerfile", "diff": "@@ -35,10 +35,10 @@ RUN sed -i -e '/pyyaml/d' /tmp/timesketch/requirements.txt\nRUN pip3 install /tmp/timesketch/\n# Copy the Timesketch configuration file into /etc\n-RUN cp /tmp/timesketch/timesketch.conf /etc\n+RUN cp /tmp/timesketch/data/timesketch.conf /etc\n# Copy Timesketch config files into /etc/timesketch\nRUN mkdir /etc/timesketch\n-RUN cp -r /tmp/timesketch/config/* /etc/timesketch/\n+RUN cp -r /tmp/timesketch/data/* /etc/timesketch/\n# Copy the entrypoint script into the container\nCOPY docker/docker-entrypoint.sh /\n" }, { "change_type": "MODIFY", "old_path": "docker/development/docker-entrypoint.sh", "new_path": "docker/development/docker-entrypoint.sh", "diff": "@@ -9,8 +9,8 @@ if [ \"$1\" = 'timesketch' ]; then\n# Copy config files\nmkdir /etc/timesketch\n- cp /usr/local/src/timesketch/timesketch.conf /etc\n- cp /usr/local/src/timesketch/config/features.yaml /etc/timesketch/\n+ cp /usr/local/src/timesketch/data/timesketch.conf /etc\n+ cp /usr/local/src/timesketch/data/features.yaml /etc/timesketch/\n# Set SECRET_KEY in /etc/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to docker configs. (#915)
263,143
26.06.2019 13:34:13
0
42fff1a0401e948460d86098560e2b65a4b525fc
gcp_servicekey usage analyzer for stackdrive log output by dftimewolf
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/gcp_servicekey.py", "new_path": "timesketch/lib/analyzers/gcp_servicekey.py", "diff": "@@ -27,8 +27,10 @@ class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\nReturns:\nString with summary of the analyzer result\n\"\"\"\n- query = ('event_subtype:compute.instances.insert AND user:*gserviceaccount*')\n- return_fields = ['message', 'event_subtype', 'event_type', 'user', 'name']\n+ # query = ('event_subtype:compute.instances.insert AND user:*gserviceaccount*')\n+ # return_fields = ['message', 'event_subtype', 'event_type', 'user', 'name']\n+ query = ('principalEmail:*gserviceaccount*')\n+ return_fields = ['message', 'principalEmail', 'methodName', 'project_name', 'service_account_display_name', 'resourceName']\n# Generator of events based on your query.\nevents = self.event_stream(\n@@ -39,15 +41,26 @@ class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\nfor event in events:\n# Fields to analyze.\nmessage = event.source.get('message')\n- event_subtype = event.source.get('event_subtype')\n- event_type = event.source.get('event_type')\n- user = event.source.get('user')\n- name = event.source.get('name')\n+ principalEmail = event.source.get('principalEmail')\n+ methodName = event.source.get('methodName')\n+ project_name = event.source.get('project_name')\n+ service_account_display_name = event.source.get('service_account_display_name')\n- if event_type == 'GCE_OPERATION_DONE':\n+ if 'CreateServiceAccount' in methodName:\nevent.add_star()\n- event.add_tags('GCP Success Event')\n- event.add_label('vm_created')\n+ event.add_label('New ServiceAccount Created')\n+\n+ if 'compute.instances.insert' in methodName:\n+ event.add_star()\n+ event.add_label('VM created')\n+\n+ if 'compute.firewalls.insert' in methodName:\n+ event.add_star()\n+ event.add_label('FW rule created')\n+\n+ if 'compute.networks.insert' in methodName:\n+ event.add_star()\n+ event.add_label('Network Insert Event')\n# Commit the event to the datastore.\nevent.commit()\n" } ]
Python
Apache License 2.0
google/timesketch
gcp_servicekey usage analyzer for stackdrive log output by dftimewolf
263,143
26.06.2019 13:55:03
0
54daa61b240c08421d4adc9cd2074a101251174f
removed old/commented code
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/gcp_servicekey.py", "new_path": "timesketch/lib/analyzers/gcp_servicekey.py", "diff": "@@ -27,12 +27,9 @@ class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\nReturns:\nString with summary of the analyzer result\n\"\"\"\n- # query = ('event_subtype:compute.instances.insert AND user:*gserviceaccount*')\n- # return_fields = ['message', 'event_subtype', 'event_type', 'user', 'name']\nquery = ('principalEmail:*gserviceaccount*')\nreturn_fields = ['message', 'principalEmail', 'methodName', 'project_name', 'service_account_display_name', 'resourceName']\n- # Generator of events based on your query.\nevents = self.event_stream(\nquery_string=query, return_fields=return_fields)\n@@ -70,7 +67,7 @@ class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\nif gcp_servicekey_counter:\nself.sketch.add_view('GCP ServiceKey activity', 'gcp_servicekey', query_string=query)\n- # TODO: Return a summary from the analyzer.\n+ # Return a summary from the analyzer.\nreturn 'GCP ServiceKey analyzer completed, {0:d} service key marked'.format(gcp_servicekey_counter)\n" } ]
Python
Apache License 2.0
google/timesketch
removed old/commented code
263,163
02.07.2019 22:39:49
-32,400
0a40b595ac34aeba39c2df507189febe5d70faa1
Fix a Python3 error by encoding before hashing
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1052,7 +1052,7 @@ class EventCreateResource(ResourceMixin, Resource):\n# We do not need a human readable filename or\n# datastore index name, so we use UUIDs here.\n- index_name = hashlib.md5(index_name_seed).hexdigest()\n+ index_name = hashlib.md5(index_name_seed.encode()).hexdigest()\nif six.PY2:\nindex_name = codecs.decode(index_name, 'utf-8')\n" } ]
Python
Apache License 2.0
google/timesketch
Fix a Python3 error by encoding before hashing (#914)
263,143
02.07.2019 21:18:54
0
e631b1ddd8e5f7be16736f79b428c439e96f0edd
addressed johan comments
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/gcp_servicekey.py", "new_path": "timesketch/lib/analyzers/gcp_servicekey.py", "diff": "@@ -26,7 +26,9 @@ class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\nReturns:\nString with summary of the analyzer result\n\"\"\"\n- query = ('principalEmail:*gserviceaccount*')\n+ # TODO: update dftimewolf stackdriver module to produce more detailed\n+ # attributes\n+ query = ('principalEmail:*gserviceaccount.com')\nreturn_fields = ['message', 'methodName']\nevents = self.event_stream(\n@@ -39,20 +41,16 @@ class GcpServiceKeySketchPlugin(interface.BaseSketchAnalyzer):\nmethodName = event.source.get('methodName')\nif 'CreateServiceAccount' in methodName:\n- event.add_star()\n- event.add_label('New ServiceAccount Created')\n+ event.add_tags(['New ServiceAccount Created'])\nif 'compute.instances.insert' in methodName:\n- event.add_star()\n- event.add_label('VM created')\n+ event.add_tags(['VM created'])\nif 'compute.firewalls.insert' in methodName:\n- event.add_star()\n- event.add_label('FW rule created')\n+ event.add_tags(['FW rule created'])\nif 'compute.networks.insert' in methodName:\n- event.add_star()\n- event.add_label('Network Insert Event')\n+ event.add_tags(['Network Insert Event'])\n# Commit the event to the datastore.\nevent.commit()\n" } ]
Python
Apache License 2.0
google/timesketch
addressed johan comments
263,098
15.07.2019 14:27:24
-7,200
b4822f3f162c8684245de86295a24d84ac95ddd9
Fixed typo in Users-guide.md.
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "@@ -112,11 +112,11 @@ Parameters:\n#### Removing groups\n-Not yet implemented\n+Not yet implemented.\n#### Managing group membership\n-Add or remove a user to a group\n+Add or remove a user to a group.\nCommand:\n```\n@@ -214,7 +214,7 @@ tsctl similarity_score\n## Concepts\n-Timesketch is built on multiple sketches, where one sketch is ussually one case.\n+Timesketch is built on multiple sketches, where one sketch is usually one case.\nEvery sketch can consist of multiple timelines with multiple views.\n### Sketches\n" } ]
Python
Apache License 2.0
google/timesketch
Fixed typo in Users-guide.md.
263,098
16.07.2019 11:56:54
-7,200
898568f3feab9646ceec6526ddfccbfa4988a4fd
Added tsctl import command to Users-Guide.md. Some other minor changes to Users-Guide.md
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Import JSON to timesketch](#import-json-to-timesketch)\n- [Purge](#purge)\n- [Search template](#search_template)\n+ - [Import](#import)\n- [similarity_score](#similarity_score)\n3. [Concepts](#concepts)\n- [Adding Timelines](#adding-timelines)\n@@ -83,13 +84,13 @@ tsctl add_user\nParameters:\n```\n---name / -n\n+--username / -u\n--password / -p (optional)\n```\nExample\n```\n-tsctl add_user --name foo\n+tsctl add_user --username foo\n```\n#### Removing users\n@@ -116,7 +117,8 @@ Not yet implemented.\n#### Managing group membership\n-Add or remove a user to a group.\n+Add or remove a user to a group. To add a user, specify the group and user. To\n+remove a user, include the -r option.\nCommand:\n```\n@@ -125,15 +127,14 @@ tsctl manage_group\nParameters:\n```\n---add / -a\n---remove / -r\n+--remove / -r (optional)\n--group / -g\n--user / -u\n```\nExample:\n```\n-tsctl manage_group -a -u user_foo -g group_bar\n+tsctl manage_group -u user_foo -g group_bar\n```\n### add_index\n@@ -205,6 +206,26 @@ Parameters:\nimport_location: Path to the yaml file to import templates.\nexport_location: Path to the yaml file to export templates.\n+### import\n+\n+Creates a new Timesketch timeline from a file. Supported file formats are: plaso, csv and jsonl.\n+\n+Command:\n+```\n+tsctl import\n+```\n+\n+Parameters:\n+```\n+--file / -f\n+--sketch_id / -s (optional)\n+--username / -f (optional)\n+--timeline_name / -n (optional)\n+```\n+\n+The sketch id is inferred from the filename if it starts with a number. The timeline name can also be generated from the filename if not specified.\n+\n+\n### similarity_score\nCommand:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -63,7 +63,7 @@ class DropDataBaseTables(Command):\nclass AddUser(Command):\n\"\"\"Create a new Timesketch user.\"\"\"\noption_list = (\n- Option('--username', '-', dest='username', required=True),\n+ Option('--username', '-u', dest='username', required=True),\nOption('--password', '-p', dest='password', required=False), )\ndef get_password_from_prompt(self):\n@@ -117,7 +117,7 @@ class GroupManager(Command):\nrequired=False,\ndefault=False),\nOption('--group', '-g', dest='group_name', required=True),\n- Option('--user', '-', dest='user_name', required=True), )\n+ Option('--user', '-u', dest='user_name', required=True), )\n# pylint: disable=arguments-differ, method-hidden\ndef run(self, remove, group_name, user_name):\n@@ -157,7 +157,7 @@ class AddSearchIndex(Command):\noption_list = (\nOption('--name', '-n', dest='name', required=True),\nOption('--index', '-i', dest='index', required=True),\n- Option('--user', '-', dest='username', required=True), )\n+ Option('--user', '-u', dest='username', required=True), )\n# pylint: disable=arguments-differ, method-hidden\ndef run(self, name, index, username):\n@@ -308,7 +308,7 @@ class ImportTimeline(Command):\noption_list = (\nOption('--file', '-f', dest='file_path', required=True),\nOption('--sketch_id', '-s', dest='sketch_id', required=False),\n- Option('--username', '-', dest='username', required=False),\n+ Option('--username', '-u', dest='username', required=False),\nOption('--timeline_name', '-n', dest='timeline_name',\nrequired=False),\n)\n" } ]
Python
Apache License 2.0
google/timesketch
Added tsctl import command to Users-Guide.md. Some other minor changes to Users-Guide.md
263,129
07.08.2019 16:58:57
-7,200
3c9b5e4e2b62626add72d468a5c0fc27caa42f91
Format error as string
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -572,7 +572,7 @@ class Sketch(BaseResource):\nresponse = self.api.session.post(resource_url, json=form_data)\nif response.status_code != 200:\nraise ValueError(\n- 'Unable to query results, with error: [{0:d}] {1:s}'.format(\n+ 'Unable to query results, with error: [{0:d}] {1!s}'.format(\nresponse.status_code, response.reason))\nresponse_json = response.json()\n" } ]
Python
Apache License 2.0
google/timesketch
Format error as string (#944)
263,096
08.08.2019 11:54:51
-7,200
99f8738bc8ccaa6cccb6ecbb3da3b7421ef5eb7c
remove label_event() per feedback from I remove the label_event() method
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -484,26 +484,6 @@ class Sketch(BaseResource):\nresponse = self.api.session.post(resource_url, json=form_data)\nreturn response.json()\n- def label_event(self, event_id, index, label_text):\n- \"\"\"\n- Adds a comment to a single event.\n-\n- Args:\n- event_id: id of the event\n- index: The Elasticsearch index name\n- label_text: text used as a label\n- Returns:\n- a json data of the query.\n- \"\"\"\n- form_data = {\"annotation\": label_text,\n- \"annotation_type\": \"label\",\n- \"events\": {\"_id\": event_id, \"_index\": index,\n- \"_type\": \"generic_event\"}}\n- resource_url = u'{0:s}/sketches/{1:d}/event/annotate/'.format(\n- self.api.api_root, self.id)\n- response = self.api.session.post(resource_url, json=form_data)\n- return response.json()\n-\ndef label_events(self, events, label_name):\n\"\"\"Labels one or more events with label_name.\n" } ]
Python
Apache License 2.0
google/timesketch
remove label_event() per feedback from @berggren I remove the label_event() method
263,093
14.08.2019 17:24:22
-7,200
bce5cb458b5278890b9c805e379ce246764a8055
install deps in Dockerfile
[ { "change_type": "MODIFY", "old_path": "docker/development/Dockerfile", "new_path": "docker/development/Dockerfile", "diff": "# Use the latest Timesketch development base image\nFROM timesketch/timesketch-dev-base:20190603\n+# Install dependencies for Timesketch\n+COPY requirements.txt /timesketch-requirements.txt\n+RUN pip3 install -r /timesketch-requirements.txt\n+\n# Copy the entrypoint script into the container\nCOPY docker/development/docker-entrypoint.sh /docker-entrypoint.sh\nRUN chmod a+x /docker-entrypoint.sh\n" }, { "change_type": "MODIFY", "old_path": "docker/development/docker-entrypoint.sh", "new_path": "docker/development/docker-entrypoint.sh", "diff": "# Run the container the default way\nif [ \"$1\" = 'timesketch' ]; then\n- # Install Timesketch from volume\n- cd /usr/local/src/timesketch && yarn install && yarn run build\n+ # Install Timesketch in editable mode from volume\npip3 install -e /usr/local/src/timesketch/\n# Copy config files\n" } ]
Python
Apache License 2.0
google/timesketch
install deps in Dockerfile (#958)
263,096
14.08.2019 17:25:04
-7,200
12eb50d9e297488bb4e9c043e19271cdc41e72f6
Better explanation of the purge command Based on that issue: I made the purge command description a better.
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "@@ -183,6 +183,11 @@ tsctl json2ts\n### Purge\n+Delete timeline permanently from Timesketch and Elasticsearch. It will alert if a timeline is still in use in a sketch and promt for confirmation before deletion.\n+\n+ Args:\n+ index_name: The name of the index in Elasticsearch\n+\nComand:\n```\ntsctl purge\n" } ]
Python
Apache License 2.0
google/timesketch
Better explanation of the purge command (#959) Based on that issue: https://github.com/google/timesketch/issues/885 I made the purge command description a better.
263,096
14.08.2019 17:26:24
-7,200
71676b516a79eac7891896a2008aab6c55783ad6
Mention SearchQueryGuide and SketchOverview in the userguide In it was still open and I have not looked at the SearchQuery Guide before, so it is worth to mention it in the Userguide Same goes for the SketchOverview document.
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Import](#import)\n- [similarity_score](#similarity_score)\n3. [Concepts](#concepts)\n+ - [Sketches](#sketches)\n- [Adding Timelines](#adding-timelines)\n- [Using Stories](#stories)\n- [Adding event](#adding-event)\n+ - [Views](#views)\n+ - [Hiding events from a view](#hiding-events-from-a-view)\n+ - [Heatmap](#heatmap)\n+ - [Stories](#stories)\n4. [Searching](#searching)\n@@ -245,6 +250,8 @@ Every sketch can consist of multiple timelines with multiple views.\n### Sketches\n+There is a dedicated document to walk you through [Sketches](/docs/SketchOverview.md)\n+\n### Adding Timelines\n* [Create timeline from JSON/JSONL/CSV file](/docs/CreateTimelineFromJSONorCSV.md)\n@@ -258,7 +265,6 @@ This event will have the previously selected time pre-filled but can be changed.\n![Add event screenshot](/docs/add_event.png)\n-\n### Views\n#### Hiding events from a view\n@@ -285,6 +291,8 @@ See [Medium article](https://medium.com/timesketch/timesketch-2016-7-db3083e7815\n## Searching\n+There is a dedicated document called [SearchQueryGuide](/docs/SearchQueryGuide.md) to help you create custom searches.\n+\nAll data within Timesketch is stored in elasticsearch. So the search works similar to ES.\nUsing the advances search, a JSON can be passed to Timesketch\n" } ]
Python
Apache License 2.0
google/timesketch
Mention SearchQueryGuide and SketchOverview in the userguide (#947) In https://github.com/google/timesketch/issues/421 it was still open and I have not looked at the SearchQuery Guide before, so it is worth to mention it in the Userguide Same goes for the SketchOverview document.
263,098
14.08.2019 17:27:33
-7,200
e55c7590d076f447664337b698904da3e1ead0bc
Fix for error when adding a view with query_dsl
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -280,7 +280,7 @@ class Sketch(object):\nReturns: An instance of a SQLAlchemy View object.\n\"\"\"\n- if not query_string or query_dsl:\n+ if not (query_string or query_dsl):\nraise ValueError('Both query_string and query_dsl are missing.')\nif not query_filter:\n" } ]
Python
Apache License 2.0
google/timesketch
Fix for error when adding a view with query_dsl (#948)
263,093
19.08.2019 13:09:35
25,200
81b203c5712c9cd0060e47eab4550e7c2027b8ae
drop Xenial from Travis tests
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "matrix:\ninclude:\n- - name: \"Pylint on Ubuntu Bionic (18.04) (Docker) with Python 3.6\"\n+ - name: \"Ubuntu Bionic (18.04) (Docker) Pylint with Python 3.6\"\nenv: [TARGET=\"pylint\", UBUNTU_VERSION=\"18.04\"]\nos: linux\ndist: xenial\n@@ -10,22 +10,6 @@ matrix:\npython: 3.6\nservices:\n- docker\n- - name: \"Ubuntu Xenial (16.04) with Python 2.7 (pip)\"\n- env: TARGET=\"linux-python27\"\n- os: linux\n- dist: xenial\n- group: edge\n- language: python\n- python: 2.7\n- node_js: '8'\n- - name: \"Ubuntu Xenial (16.04) with Python 3.6 (pip)\"\n- env: TARGET=\"linux-python36\"\n- os: linux\n- dist: xenial\n- group: edge\n- language: python\n- python: 3.6\n- node_js: '8'\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 2.7\"\nenv: UBUNTU_VERSION=\"18.04\"\nos: linux\n" } ]
Python
Apache License 2.0
google/timesketch
drop Xenial from Travis tests (#963)
263,133
26.09.2019 10:06:59
0
c9e4d01a3897f5dcc361ca94143c48ee4857d3e9
Making changes to the client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20190925',\n+ version='20190926',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -367,45 +367,20 @@ class Sketch(BaseResource):\nreturn data_frame\n- def _get_aggregation_buckets(self, entry, name=''):\n- \"\"\"Yields all buckets from a aggregation result object.\n-\n- Args:\n- entry: result dict from an aggregation request.\n- name: name of aggregation results that contains\n- all aggregation buckets.\n-\n- Yields:\n- A dict with each aggregation bucket as well as\n- the bucket_name.\n- \"\"\"\n- if 'buckets' in entry:\n- for bucket in entry.get('buckets', []):\n- bucket['bucket_name'] = name\n- yield bucket\n- else:\n- for key, value in iter(entry.items()):\n- if not isinstance(value, dict):\n- continue\n- for bucket in self._get_aggregation_buckets(\n- value, name=key):\n- yield bucket\n-\ndef list_aggregations(self):\n\"\"\"List all saved aggregations for this sketch.\nReturns:\nList of aggregations (instances of Aggregation objects)\n\"\"\"\n- sketch = self.lazyload_data()\n+ data = self.lazyload_data()\naggregations = []\n- for aggregation in sketch['meta']['saved_aggregations']:\n+ for aggregation in data['meta']['saved_aggregations']:\naggregation_obj = Aggregation(\n+ sketch=self, api=self.api)\n+ aggregation_obj.from_store(\naggregation_id=aggregation['id'],\n- aggregation_name=aggregation['name'],\n- sketch=self,\n- sketch_id=self.id,\n- api=self.api)\n+ aggregation_name=aggregation['name'])\naggregations.append(aggregation_obj)\nreturn aggregations\n@@ -423,12 +398,10 @@ class Sketch(BaseResource):\nfor aggregation in sketch['meta']['saved_aggregations']:\nif aggregation['id'] != aggregation_id:\ncontinue\n- aggregation_obj = Aggregation(\n+ aggregation_obj = Aggregation(sketch=self, api=self.api)\n+ aggregation_obj.from_store(\naggregation_id=aggregation['id'],\n- aggregation_name=aggregation['name'],\n- sketch=self,\n- sketch_id=self.id,\n- api=self.api)\n+ aggregation_name=aggregation['name'])\nreturn aggregation_obj\ndef list_views(self):\n@@ -625,17 +598,14 @@ class Sketch(BaseResource):\nreturn response_json\n- def aggregate(self, aggregate_dsl, as_pandas=False):\n+ def aggregate(self, aggregate_dsl):\n\"\"\"Run an aggregation request on the sketch.\nArgs:\naggregate_dsl: Elasticsearch aggregation query DSL string.\n- as_pandas: Optional bool that determines if the results should\n- be returned back as a dictionary or a Pandas DataFrame.\nReturns:\n- Dictionary with query results or a pandas DataFrame if as_pandas\n- is set to True.\n+ An aggregation object (instance of Aggregation).\nRaises:\nValueError: if unable to query for the results.\n@@ -644,69 +614,53 @@ class Sketch(BaseResource):\nraise RuntimeError(\n'You need to supply an aggregation query DSL string.')\n- resource_url = '{0:s}/sketches/{1:d}/aggregation/explore/'.format(\n- self.api.api_root, self.id)\n-\n- form_data = {\n- 'aggregation_dsl': aggregate_dsl,\n- }\n-\n- response = self.api.session.post(resource_url, json=form_data)\n- if response.status_code != 200:\n- raise ValueError(\n- 'Unable to query results, with error: [{0:d}] {1:s}'.format(\n- response.status_code, response.reason))\n+ aggregation_obj = Aggregation(sketch=self, api=self.api)\n+ aggregation_obj.from_explore(aggregate_dsl)\n- response_json = response.json()\n-\n- if as_pandas:\n- panda_list = []\n- for entry in response_json.get('objects', []):\n- for bucket in self._get_aggregation_buckets(entry):\n- panda_list.append(bucket)\n- return pandas.DataFrame(panda_list)\n+ return aggregation_obj\n- return response_json\n+ # TODO : Add a way to list all available aggregators\n+ def list_available_aggregators(self):\n+ \"\"\"TODO\"\"\"\n+ data = self.lazyload_data()\n+ meta = data.get('meta', {})\n+ entries = []\n+ for name, options in iter(meta.get('aggregators', {}).items()):\n+ for field in options.get('form_fields', []):\n+ entry = {\n+ 'aggregator_name': name,\n+ 'parameter': field.get('name'),\n+ 'label': field.get('label')\n+ }\n+ if field.get('type') == 'ts-dynamic-form-select-input':\n+ entry['value'] = '|'.join(field.get('options', []))\n+ else:\n+ _, _, entry['type'] = field.get('type').partition(\n+ 'ts-dynamic-form-')\n+ entries.append(entry)\n+ return pandas.DataFrame(entries)\ndef run_aggregator(\n- self, aggregator_name, aggregator_parameters, as_pandas=False):\n+ self, aggregator_name, aggregator_parameters):\n\"\"\"Run an aggregator class.\nArgs:\naggregator_name: Name of the aggregator to run.\naggregator_parameters: A dict with key/value pairs of parameters\nthe aggregator needs to run.\n- as_pandas: Optional bool that determines if the results should\n- be returned back as a dictionary or a Pandas DataFrame.\nReturns:\n- Dictionary with query results or a pandas DataFrame if as_pandas\n- is set to True.\n+ An aggregation object (instance of Aggregator).\n\"\"\"\n- resource_url = '{0:s}/sketches/{1:d}/aggregation/explore/'.format(\n- self.api.api_root, self.id)\n-\n- form_data = {\n- 'aggregator_name': aggregator_name,\n- 'aggregator_parameters': aggregator_parameters,\n- }\n-\n- response = self.api.session.post(resource_url, json=form_data)\n- if response.status_code != 200:\n- raise ValueError(\n- 'Unable to query results, with error: [{0:d}] {1:s}'.format(\n- response.status_code, response.reason))\n-\n- response_json = response.json()\n-\n- if as_pandas:\n- panda_list = []\n- for entry in response_json.get('objects', []):\n- for bucket in self._get_aggregation_buckets(entry):\n- panda_list.append(bucket)\n- return pandas.DataFrame(panda_list)\n+ aggregation_obj = Aggregation(\n+ sketch=self,\n+ api=self.api)\n+ aggregation_obj.from_aggregator_run(\n+ aggregator_name=aggregator_name,\n+ aggregator_parameters=aggregator_parameters\n+ )\n- return response_json\n+ return aggregation_obj\ndef store_aggregation(\nself, name, description, aggregator_name, aggregator_parameters,\n@@ -865,81 +819,232 @@ class SearchIndex(BaseResource):\nclass Aggregation(BaseResource):\n- \"\"\"Saved aggregation object.\n+ \"\"\"Aggregation object.\nAttributes:\n- id: Primary key of the aggregation.\n- name: Name of the aggregation.\n+ aggregator_name: name of the aggregator class used to\n+ generate the aggregation.\n+ chart_type: the type of chart that will be generated\n+ from this aggregation object.\n+ type: the type of aggregation object.\n+ view: a view ID if the aggregation is tied to a specific view.\n\"\"\"\ndef __init__(\n- self, aggregation_id, aggregation_name, sketch, sketch_id, api):\n- self.id = aggregation_id\n- self.name = aggregation_name\n+ self, sketch, api):\nself._sketch = sketch\n- resource_uri = 'sketches/{0:d}/aggregation/{1:d}/'.format(\n- sketch_id, aggregation_id)\n+ self._aggregator_data = {}\n+ self._parameters = {}\n+ self.aggregator_name = ''\n+ self.chart_type = ''\n+ self.view = None\n+ self.type = None\n+ resource_uri = 'sketches/{0:d}/aggregation/explore/'.format(sketch.id)\nsuper(Aggregation, self).__init__(api, resource_uri)\n- def _aggregation(self):\n- \"\"\"Return the aggregation object.\"\"\"\n- data = self.lazyload_data()\n- return data.get('objects', [])[0]\n+ def _get_aggregation_buckets(self, entry, name=''):\n+ \"\"\"Yields all buckets from a aggregation result object.\n- @property\n- def agg_type(self):\n- \"\"\"Property that returns the agg_type string.\"\"\"\n- aggregation = self._aggregation()\n- return aggregation.get('agg_type', '')\n+ Args:\n+ entry: result dict from an aggregation request.\n+ name: name of aggregation results that contains\n+ all aggregation buckets.\n+\n+ Yields:\n+ A dict with each aggregation bucket as well as\n+ the bucket_name.\n+ \"\"\"\n+ if 'buckets' in entry:\n+ for bucket in entry.get('buckets', []):\n+ bucket['bucket_name'] = name\n+ yield bucket\n+ else:\n+ for key, value in iter(entry.items()):\n+ if not isinstance(value, dict):\n+ continue\n+ for bucket in self._get_aggregation_buckets(\n+ value, name=key):\n+ yield bucket\n+\n+ def _run_aggregator(\n+ self, aggregator_name, parameters, view_id=None, chart_type=None):\n+ \"\"\"Run an aggregator class.\n+\n+ Args:\n+ aggregator_name: the name of the aggregator class.\n+ parameters: a dict with the parameters for the aggregation class.\n+ view_id: an optional integer value with a primary key to a view.\n+ chart_type: string with the chart type.\n+\n+ Returns:\n+ A dict with the aggregation results.\n+ \"\"\"\n+ resource_url = '{0:s}/sketches/{1:d}/aggregation/explore/'.format(\n+ self.api.api_root, self._sketch.id)\n+ if chart_type is None and parameters.get('supported_charts'):\n+ chart_type = parameters.get('supported_charts')\n+ if isinstance(chart_type, (list, tuple)):\n+ chart_type = chart_type[0]\n+\n+ if chart_type:\n+ self.chart_type = chart_type\n+\n+ if view_id:\n+ self.view = view_id\n+\n+ self.aggregator_name = aggregator_name\n+\n+ form_data = {\n+ 'aggregator_name': aggregator_name,\n+ 'aggregator_parameters': parameters,\n+ 'chart_type': chart_type,\n+ 'view_id': view_id,\n+ }\n+\n+ response = self.api.session.post(resource_url, json=form_data)\n+ if response.status_code != 200:\n+ raise ValueError(\n+ 'Unable to query results, with error: [{0:d}] {1:s}'.format(\n+ response.status_code, response.reason))\n+\n+ return response.json()\n+\n+ def from_store(self, aggregation_id, aggregation_name):\n+ \"\"\"Initialize the aggregation object from a stored aggregation.\n+\n+ Args:\n+ aggregation_id: integer value for the stored aggregation (primary key).\n+ aggregation_name: the name of the aggregation.\n+ \"\"\"\n+ resource_uri = 'sketches/{0:d}/aggregation/{1:d}/'.format(\n+ self._sketch.id, aggregation_id)\n+ resource_data = self.api.fetch_resource_data(resource_uri)\n+ data = resource_data.get('objects', [None])[0]\n+ if not data:\n+ return\n+\n+ self._aggregator_data = data\n+ self.aggregator_name = data.get('agg_type')\n+ self.type = 'stored'\n+\n+ chart_type = data.get('chart_type')\n+ agg_name = data.get('name')\n+ param_string = data.get('parameters', '')\n+ if param_string:\n+ parameters = json.loads(param_string)\n+ else:\n+ parameters = {}\n+\n+ self._parameters = parameters\n+ self.resource_data = self._run_aggregator(\n+ aggregator_name=agg_name, parameters=parameters, chart_type=chart_type)\n+\n+ def from_explore(self, aggregate_dsl):\n+ \"\"\"Initialize the aggregation object by running an aggregation DSL.\n+\n+ Args:\n+ aggregate_dsl: Elasticsearch aggregation query DSL string.\n+ \"\"\"\n+ resource_url = '{0:s}/sketches/{1:d}/aggregation/explore/'.format(\n+ self.api.api_root, self._sketch.id)\n+\n+ self.aggregator_name = 'DSL'\n+ self.type = 'DSL'\n+\n+ form_data = {\n+ 'aggregation_dsl': aggregate_dsl,\n+ }\n+\n+ response = self.api.session.post(resource_url, json=form_data)\n+ if response.status_code != 200:\n+ raise ValueError(\n+ 'Unable to query results, with error: [{0:d}] {1:s}'.format(\n+ response.status_code, response.reason))\n+\n+ self.resource_data = response.json()\n+\n+ def from_aggregator_run(\n+ self, aggregator_name, aggregator_parameters,\n+ view_id=None, chart_type=None):\n+ \"\"\"Initialize the aggregation object by running an aggregator class.\n+\n+ Args:\n+ aggregator_name: name of the aggregator class to run.\n+ aggregator_parameters: a dict with the parameters of the aggregator\n+ class.\n+ view_id: an optional integer value with a primary key to a view.\n+ chart_type: optional string with the chart type.\n+ \"\"\"\n+ self.type = 'aggregator_run'\n+ self._parameters = aggregator_parameters\n+ self.resource_data = self._run_aggregator(\n+ aggregator_name, aggregator_parameters, view_id, chart_type)\n+\n+ def lazyload_data(self, refresh_cache=False):\n+ \"\"\"Load resource data once and cache the result.\n+\n+ Args:\n+ refresh_cache: Boolean indicating if to update cache.\n+\n+ Returns:\n+ Dictionary with resource data.\n+ \"\"\"\n+ if self.resource_data and not refresh_cache:\n+ return self.resource_data\n+\n+ # TODO: Implement a method to refresh cache.\n+ return self.resource_data\n@property\ndef chart(self):\n\"\"\"Property that returns an altair Vega-lite chart.\"\"\"\nreturn self.generate_chart()\n- @property\n- def chart_type(self):\n- \"\"\"Property that returns the chart_type string.\"\"\"\n- aggregation = self._aggregation()\n- return aggregation.get('chart_type', '')\n-\n@property\ndef description(self):\n\"\"\"Property that returns the description string.\"\"\"\n- aggregation = self._aggregation()\n- return aggregation.get('description', '')\n+ return self._aggregator_data.get('description', '')\n@property\n- def view(self):\n- \"\"\"Property that returns the view_id integer.\"\"\"\n- aggregation = self._aggregation()\n- return aggregation.get('view_id', 0)\n+ def id(self):\n+ \"\"\"Property that returns the ID of the aggregator, if possible.\"\"\"\n+ agg_id = self._aggregator_data.get('id')\n+ if agg_id:\n+ return agg_id\n+\n+ return -1\n@property\n- def parameters(self):\n- \"\"\"Property that returns the parameter dict.\"\"\"\n- aggregation = self._aggregation()\n- param_string = aggregation.get('parameters', '')\n- if not param_string:\n- return {}\n- return json.loads(param_string)\n+ def name(self):\n+ \"\"\"Property that returns the name of the aggregation.\"\"\"\n+ name = self._aggregator_data.get('name')\n+ if name:\n+ return name\n+ return self.aggregator_name\n@property\ndef table(self):\n\"\"\"Property that returns a pandas DataFrame.\"\"\"\n- return self.run(as_pandas=True)\n+ return self.to_pandas()\n+\n+ def to_pandas(self):\n+ \"\"\"Returns a pandas DataFrame.\"\"\"\n+ panda_list = []\n+ data = self.lazyload_data()\n+ for entry in data.get('objects', []):\n+ for bucket in self._get_aggregation_buckets(entry):\n+ panda_list.append(bucket)\n+ return pandas.DataFrame(panda_list)\ndef generate_chart(self):\n\"\"\"Returns an altair Vega-lite chart.\"\"\"\nif not self.chart_type:\n- return altair.Chart(pandas.DataFrame()).mark_point()\n+ raise TypeError('Unable to generate chart, missing a chart type.')\n- if not self.parameters.get('supported_charts'):\n+ if not self._parameters.get('supported_charts'):\nself.parameters['supported_charts'] = self.chart_type\n- data = self._sketch.run_aggregator(\n- self.name, self.parameters, as_pandas=False)\n-\n+ data = self.lazyload_data()\nmeta = data.get('meta', {})\nvega_spec = meta.get('vega_spec')\n@@ -949,11 +1054,6 @@ class Aggregation(BaseResource):\nvega_spec_string = json.dumps(vega_spec)\nreturn altair.Chart.from_json(vega_spec_string)\n- def run(self, as_pandas=False):\n- \"\"\"Returns the results from an aggregator run.\"\"\"\n- return self._sketch.run_aggregator(\n- self.name, self.parameters, as_pandas=as_pandas)\n-\nclass View(BaseResource):\n\"\"\"Saved view object.\n" } ]
Python
Apache License 2.0
google/timesketch
Making changes to the client.
263,133
26.09.2019 10:14:04
0
5c338e962d659069e02490d022963d061bda7831
Fixing listing aggregators.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -615,9 +615,8 @@ class Sketch(BaseResource):\nreturn aggregation_obj\n- # TODO : Add a way to list all available aggregators\ndef list_available_aggregators(self):\n- \"\"\"TODO\"\"\"\n+ \"\"\"Return a list of all available aggregators in the sketch.\"\"\"\ndata = self.lazyload_data()\nmeta = data.get('meta', {})\nentries = []\n@@ -626,10 +625,11 @@ class Sketch(BaseResource):\nentry = {\n'aggregator_name': name,\n'parameter': field.get('name'),\n- 'label': field.get('label')\n+ 'notes': field.get('label')\n}\nif field.get('type') == 'ts-dynamic-form-select-input':\nentry['value'] = '|'.join(field.get('options', []))\n+ entry['type'] = 'selection'\nelse:\n_, _, entry['type'] = field.get('type').partition(\n'ts-dynamic-form-')\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing listing aggregators.
263,133
26.09.2019 12:44:59
0
ffab694a8dc0f82bad6406c12f5b56b552e57ecd
adding a to_dict
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -1019,11 +1019,27 @@ class Aggregation(BaseResource):\nreturn name\nreturn self.aggregator_name\n+ @property\n+ def dict(self):\n+ \"\"\"Property that returns back a Dict with the results.\"\"\"\n+ return self.to_dict()\n+\n@property\ndef table(self):\n\"\"\"Property that returns a pandas DataFrame.\"\"\"\nreturn self.to_pandas()\n+ def to_dict(self):\n+ \"\"\"Returns a dict.\"\"\"\n+ entries = {}\n+ entry_index = 1\n+ data = self.lazyload_data()\n+ for entry in data.get('objects', []):\n+ for bucket in self._get_aggregation_buckets(entry):\n+ entries['entry_{0:d}'.format(entry_index)] = bucket\n+ entry_index += 1\n+ return entries\n+\ndef to_pandas(self):\n\"\"\"Returns a pandas DataFrame.\"\"\"\npanda_list = []\n" } ]
Python
Apache License 2.0
google/timesketch
adding a to_dict
263,133
26.09.2019 13:56:23
0
fefd80f8239a9fa619329f98cdcfa0f36579657c
Minor bug in client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20190926',\n+ version='20190927',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -877,6 +877,7 @@ class Aggregation(BaseResource):\n\"\"\"\nresource_url = '{0:s}/sketches/{1:d}/aggregation/explore/'.format(\nself.api.api_root, self._sketch.id)\n+\nif chart_type is None and parameters.get('supported_charts'):\nchart_type = parameters.get('supported_charts')\nif isinstance(chart_type, (list, tuple)):\n@@ -924,7 +925,6 @@ class Aggregation(BaseResource):\nself.type = 'stored'\nchart_type = data.get('chart_type')\n- agg_name = data.get('name')\nparam_string = data.get('parameters', '')\nif param_string:\nparameters = json.loads(param_string)\n@@ -933,7 +933,7 @@ class Aggregation(BaseResource):\nself._parameters = parameters\nself.resource_data = self._run_aggregator(\n- aggregator_name=agg_name, parameters=parameters,\n+ aggregator_name=self.aggregator_name, parameters=parameters,\nchart_type=chart_type)\ndef from_explore(self, aggregate_dsl):\n" } ]
Python
Apache License 2.0
google/timesketch
Minor bug in client.
263,133
26.09.2019 18:22:42
0
2b335b9f83624a819d1569f3764a7eca0f38641e
Upgrading jupyter notebook.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -1055,7 +1055,7 @@ class Aggregation(BaseResource):\nraise TypeError('Unable to generate chart, missing a chart type.')\nif not self._parameters.get('supported_charts'):\n- self.parameters['supported_charts'] = self.chart_type\n+ self._parameters['supported_charts'] = self.chart_type\ndata = self.lazyload_data()\nmeta = data.get('meta', {})\n" }, { "change_type": "MODIFY", "old_path": "notebooks/jupyter-timesketch-demo.ipynb", "new_path": "notebooks/jupyter-timesketch-demo.ipynb", "diff": "\"outputs\": [],\n\"source\": [\n\"# This works in a Jupyter notebook settings. Uncomment if you are using a jupyter notebook.\\n\",\n+ \"# (you'll need to have installed vega)\\n\",\n\"#alt.renderers.enable('notebook')\"\n]\n},\n\"data[(data.datetime > '2015-08-29 12:21:04') & (data.datetime < '2015-08-29 12:21:08')][['datetime', 'message', 'timestamp_desc']]\"\n]\n},\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"## Let's look at aggregation\\n\",\n+ \"\\n\",\n+ \"Timesketch also has aggregation capabilities that we can call from the client. Let's take a quick look.\\n\",\n+ \"\\n\",\n+ \"Start by checking out whether there are any stored aggregations that we can just take a look at.\\n\",\n+ \"\\n\",\n+ \"You can also store your own aggregations using the `gd_sketch.store_aggregation` function. However we are not going to do that in this colab.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"gd_sketch.list_aggregations()\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"OK, so there are some aggregations stored. Let's just pick one of those to take a closer look at.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregation = gd_sketch.list_aggregations()[0]\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"Now we've got an aggregation object that we can take a closer look at.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregation.name\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregation.description\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\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+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"pd.DataFrame([{'name': x.name, 'description': x.description} for x in gd_sketch.list_aggregations()])\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"Let's look at the aggregation visually, both as a table and a chart.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregation.table\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregation.chart\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\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+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"gd_sketch.list_available_aggregators()\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"Now we can see that there are at least the \\\"field_bucket\\\" and \\\"query_bucket\\\" aggregators that we can look at. The `field_bucket` one is a terms bucket aggregation, which means we can take any field in the dataset and aggregate on that.\\n\",\n+ \"\\n\",\n+ \"So if we want to for instance see the top 20 domains that were visited we can just ask for an aggregation of the field `domain` and limit it to 20 records (which will be the top 20). Let's do that:\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregator = gd_sketch.run_aggregator(\\n\",\n+ \" aggregator_name='field_bucket',\\n\",\n+ \" aggregator_parameters={'field': 'domain', 'limit': 20, 'supported_charts': 'barchart'})\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"Now we've got an aggregation object that we can take a closer look at... let's look at the data it stored. What we were trying to get out was the top 20 domains that were visited.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregator.table\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"Or we can look at this visually... as a chart\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"aggregator.chart\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"We can also do something a bit more complex. The other aggregator, the `query_bucket` works in a similar way, except you can filter the results first. We want to aggregate all the domains that have been tagged with the phishy domain tag.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"tag_aggregator = gd_sketch.run_aggregator(\\n\",\n+ \" aggregator_name='query_bucket',\\n\",\n+ \" aggregator_parameters={\\n\",\n+ \" 'field': 'domain',\\n\",\n+ \" 'query_string': 'tag:\\\"phishy-domain\\\"',\\n\",\n+ \" 'supported_charts': 'barchart',\\n\",\n+ \" }\\n\",\n+ \")\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"Let's look at the results.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"tag_aggregator.table\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"We can also look at all the tags in the timeline. What tags have been applied and how frequent are they.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"gd_sketch.run_aggregator(\\n\",\n+ \" aggregator_name='field_bucket',\\n\",\n+ \" aggregator_parameters={\\n\",\n+ \" 'field': 'tag',\\n\",\n+ \" 'limit': 10,\\n\",\n+ \" }\\n\",\n+ \").table\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"And then to see what are the most frequent applications executed on the machine.\\n\",\n+ \"\\n\",\n+ \"Since not all of the execution events have the same fields in them we'll have to create few tables here... let's start with looking at what data types are there.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"gd_sketch.run_aggregator(\\n\",\n+ \" aggregator_name='query_bucket',\\n\",\n+ \" aggregator_parameters={\\n\",\n+ \" 'field': 'data_type',\\n\",\n+ \" 'query_string': 'tag:\\\"application_execution\\\"',\\n\",\n+ \" 'supported_charts': 'barchart',\\n\",\n+ \" }\\n\",\n+ \").table\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {},\n+ \"source\": [\n+ \"And then we can do a summary for each one.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\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+ \" 'supported_charts': 'barchart',\\n\",\n+ \" }\\n\",\n+ \").table\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"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+ \" }\\n\",\n+ \").table\"\n+ ]\n+ },\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n\"name\": \"python\",\n\"nbconvert_exporter\": \"python\",\n\"pygments_lexer\": \"ipython3\",\n- \"version\": \"3.5.4rc1\"\n+ \"version\": \"3.6.4\"\n}\n},\n\"nbformat\": 4,\n" } ]
Python
Apache License 2.0
google/timesketch
Upgrading jupyter notebook. (#985)
263,133
14.10.2019 23:06:33
-7,200
e3fb7057348f30f7980b4373e5fdebad93a69606
Minor changes and adding a test.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain.py", "new_path": "timesketch/lib/analyzers/chain.py", "diff": "@@ -28,7 +28,7 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\n\"\"\"\nself.index_name = index_name\nself._chain_plugins = (\n- chain_manager.ChainPluginsManager.GetPlugins())\n+ chain_manager.ChainPluginsManager.GetPlugins(self))\nsuper(ChainSketchPlugin, self).__init__(index_name, sketch_id)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_plugins/interface.py", "new_path": "timesketch/lib/analyzers/chain_plugins/interface.py", "diff": "@@ -29,6 +29,11 @@ class BaseChainPlugin(object):\n_EMOJIS = [emojis.get_emoji('LINK')]\n+ def __init__(self, analyzer_object):\n+ \"\"\"Initialize the plugin.\"\"\"\n+ super(BaseChainPlugin, self).__init__()\n+ self.analyzer_object = analyzer_object\n+\ndef ProcessChain(self, base_event):\n\"\"\"Determine if the extracted event fits the criteria of the plugin.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_plugins/manager.py", "new_path": "timesketch/lib/analyzers/chain_plugins/manager.py", "diff": "@@ -26,13 +26,16 @@ class ChainPluginsManager(object):\ndel cls._plugin_classes[plugin_name]\n@classmethod\n- def GetPlugins(cls):\n+ def GetPlugins(cls, analyzer_object):\n\"\"\"Retrieves the chain plugins.\n+ Args:\n+ analyzer_object: an instance of Sketch object.\n+\nReturns:\nlist[type]: list of all chain plugin objects.\n\"\"\"\n- return [plugin_class() for plugin_class in iter(\n+ return [plugin_class(analyzer_object) for plugin_class in iter(\ncls._plugin_classes.values())]\n@classmethod\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_plugins/win_prefetch.py", "new_path": "timesketch/lib/analyzers/chain_plugins/win_prefetch.py", "diff": "@@ -26,7 +26,7 @@ class WinPrefetchChainPlugin(interface.BaseChainPlugin):\nboolean to determine whether a chain should be generated from\nthe event or not. By default this returns True.\n\"\"\"\n- target = event.source.get('executable', '')\n+ target = base_event.source.get('executable', '')\nreturn target.lower().endswith('.exe')\ndef GetChainedEvents(self, base_event):\n@@ -48,7 +48,8 @@ class WinPrefetchChainPlugin(interface.BaseChainPlugin):\nsearch_query = 'url:\"*{0:s}\"'.format(target)\nreturn_fields = ['url']\n- events = self.event_stream(search_query, return_fields=return_fields)\n+ events = self.analyzer_object.event_stream(\n+ search_query, return_fields=return_fields)\nfor event in events:\nurl = event.source.get('url', '')\nif target.lower() in url.lower():\n@@ -57,7 +58,8 @@ class WinPrefetchChainPlugin(interface.BaseChainPlugin):\nlnk_query = 'parser:lnk'\nreturn_fields = ['link_target']\n- events = self.event_stream(lnk_query, return_fields=return_fields)\n+ events = self.analyzer_object.event_stream(\n+ lnk_query, return_fields=return_fields)\nfor event in events:\nlink_target = event.source.get('link_target', '')\nif target.lower() in link_target.lower():\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/chain_test.py", "diff": "+\"\"\"Tests for Chain analyzer.\"\"\"\n+from __future__ import unicode_literals\n+\n+import mock\n+\n+from timesketch.lib.analyzers import chain\n+from timesketch.lib.analyzers.chain_plugins import interface\n+from timesketch.lib.analyzers.chain_plugins import manager\n+\n+from timesketch.lib.testlib import BaseTest\n+from timesketch.lib.testlib import MockDataStore\n+\n+\n+class FakeEvent(object):\n+ \"\"\"Fake event object.\"\"\"\n+\n+ def __init__(self, source_dict):\n+ self.source = source_dict\n+\n+ def add_attributes(self, unusued_attributes):\n+ pass\n+\n+ def add_emojis(self, unused_list):\n+ pass\n+\n+ def commit(self):\n+ pass\n+\n+\n+class FakeAnalyzer(chain.ChainSketchPlugin):\n+ \"\"\"Fake analyzer object used for \"finding events\".\"\"\"\n+\n+ def event_stream(self, search_query, return_fields):\n+ \"\"\"Yields few test events.\"\"\"\n+ event_one = FakeEvent({\n+ 'url': 'http://minsida.biz',\n+ 'stuff': 'foo'})\n+\n+ yield event_one\n+\n+ event_two = FakeEvent({\n+ 'url': 'http://onnursida.biz',\n+ 'stuff': 'bar',\n+ 'annad': 'lesa_um_mig_herna',\n+ 'tenging': 'ekki satt'})\n+\n+ yield event_two\n+\n+ event_three = FakeEvent({\n+ 'tenging': 'klarlega',\n+ 'gengur': 'bara svona lala',\n+ 'url': 'N/A'})\n+\n+ yield event_three\n+\n+\n+class FakeChainPlugin(interface.BaseChainPlugin):\n+ \"\"\"Fake chain plugin.\"\"\"\n+\n+ NAME = 'fake_chain'\n+ DESCRIPTION = 'Fake plugin for the chain analyzer.'\n+ SEARCH_QUERY = 'give me all the data'\n+ EVENT_FIELDS = ['kedjur']\n+\n+ def ProcessChain(self, base_event):\n+ return True\n+\n+ def GetChainedEvents(self, base_event):\n+ url = base_event.source.get('url', '')\n+ tenging = base_event.source.get('tenging', '')\n+\n+ if url == 'http://onnursida.biz':\n+ yield FakeEvent({'domain': 'minn en ekki thinn'})\n+ yield FakeEvent({'some_bar': 'foo'})\n+ elif tenging == 'klarlega':\n+ yield FakeEvent({'stuff': 'yes please'})\n+ else:\n+ yield FakeEvent({'a': 'q'})\n+ yield FakeEvent({'b': 'w'})\n+ yield FakeEvent({'c': 'e'})\n+ yield FakeEvent({'d': 'r'})\n+ yield FakeEvent({'e': 't'})\n+ yield FakeEvent({'f': 'y'})\n+\n+\n+class TestChainAnalyzer(BaseTest):\n+ \"\"\"Tests the functionality of the analyzer.\"\"\"\n+\n+ def setUp(self):\n+ \"\"\"Setting the test up.\"\"\"\n+ for plugin in manager.ChainPluginsManager.GetPlugins(None):\n+ manager.ChainPluginsManager.DeregisterPlugin(plugin)\n+\n+ manager.ChainPluginsManager.RegisterPlugin(FakeChainPlugin)\n+\n+ @mock.patch('timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore)\n+ def test_get_chains(self):\n+ \"\"\"Test the chain.\"\"\"\n+ analyzer = FakeAnalyzer('test_index', sketch_id=1)\n+ analyzer.datastore.client = mock.Mock()\n+\n+ plugins = manager.ChainPluginsManager.GetPlugins(analyzer)\n+ self.assertEqual(len(plugins), 1)\n+\n+ plugin = plugins[0]\n+\n+ #message = analyzer.run()\n+ #self.assertText(message, 'not right')\n+\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes and adding a test.
263,133
18.10.2019 09:03:01
0
b4b08dc82d05cb153bb62a37351a1e5fba5e7548
Adding a TODO into the code
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain.py", "new_path": "timesketch/lib/analyzers/chain.py", "diff": "@@ -42,6 +42,9 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\nnumber_of_base_events = 0\ncounter = collections.Counter()\n+ # TODO: Have each plugin run in a separate task.\n+ # TODO: Add a time limit for each plugins run to prevent it from\n+ # holding everything up.\nfor chain_plugin in self._chain_plugins:\nif chain_plugin.SEARCH_QUERY_DSL:\nsearch_dsl = chain_plugin.SEARCH_QUERY_DSL\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a TODO into the code
263,167
18.10.2019 13:17:28
25,200
0659a9b184a41c40f4b00a591beeadce0e6b7b9b
Fixed the TypeError: delimiter must be string, not unicode error when importing data into timesketch by adding a check for the delimiter type and decoding it if it isn't a string.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/utils.py", "new_path": "timesketch/lib/utils.py", "diff": "@@ -24,6 +24,8 @@ import random\nimport smtplib\nimport sys\nimport time\n+import six\n+import codecs\nfrom dateutil import parser\nfrom flask import current_app\n@@ -58,6 +60,10 @@ def read_and_validate_csv(path, delimiter=','):\n# Columns that must be present in the CSV file\nmandatory_fields = ['message', 'datetime', 'timestamp_desc']\n+ # Ensures delimiter is a string\n+ if not isinstance(delimiter, six.text_type):\n+ delimiter = codecs.decode(delimiter, 'utf8')\n+\nwith open(path, 'r', encoding='utf-8') as fh:\nreader = csv.DictReader(fh, delimiter=delimiter)\ncsv_header = reader.fieldnames\n" } ]
Python
Apache License 2.0
google/timesketch
Fixed the TypeError: delimiter must be string, not unicode error when importing data into timesketch by adding a check for the delimiter type and decoding it if it isn't a string.
263,133
22.10.2019 10:00:48
0
1b41ef393861bdb2a68f3f71ea8812cb595201b8
Updating the documentation for CSV/JSON lines uploads Updating the documentation for importing timelines into TS from CSV and JSON Lines files.
[ { "change_type": "MODIFY", "old_path": "docs/CreateTimelineFromJSONorCSV.md", "new_path": "docs/CreateTimelineFromJSONorCSV.md", "diff": "@@ -27,7 +27,42 @@ Unlike JSON files, imports in JSONL format can be streamed from disk, making the\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-Then you can create a new Timesketch timeline from the file:\n+## Using tsctl To Import Files\n- $ tsctl csv2ts --name my_timeline --file timeline.csv\n- $ tsctl jsonl2ts --name my_timeline --file timeline.jsonl\n+The command line tool `tsctl` can be used to import timelines from files. To get access to the help file for the tool use:\n+\n+```\n+$ tsctl import -?\n+usage: tsctl import [-?] --file FILE_PATH [--sketch_id SKETCH_ID]\n+ [--username USERNAME] [--timeline_name TIMELINE_NAME]\n+\n+Create a new Timesketch timeline from a file.\n+\n+optional arguments:\n+ -?, --help show this help message and exit\n+ --file FILE_PATH, -f FILE_PATH\n+ --sketch_id SKETCH_ID, -s SKETCH_ID\n+ --username USERNAME, -u USERNAME\n+ --timeline_name TIMELINE_NAME, -n TIMELINE_NAME\n+```\n+\n+An example command line to import a JSON lines file is:\n+\n+```\n+$ tsctl import --sketch_id <SKETCH_ID> --file <FILENAME>.jsonl --timeline_name <NAME_FOR_TIMELINE> --username <USER>\n+\n+Imported /PATH/FILENAME.jsonl to sketch: SKETCH_ID (<SKETCH_DESCRIPTION>)\n+```\n+\n+or an example:\n+\n+```\n+$ tsctl import --sketch_id 1 --file foo.jsonl --timeline_name testing --username dev\n+Imported /tmp/foo.jsonl to sketch: 1 (My very first sketch)\n+```\n+\n+or:\n+```\n+$ tsctl import --sketch_id 1 --file foo.csv --timeline_name testing_csv --username dev\n+Imported /tmp/foo.csv to sketch: 1 (My very first sketch)\n+```\n" } ]
Python
Apache License 2.0
google/timesketch
Updating the documentation for CSV/JSON lines uploads Updating the documentation for importing timelines into TS from CSV and JSON Lines files.
263,133
22.10.2019 15:36:38
0
9d891a71ae3a569146fa026b50d880611d7d3551
Adding list sketches to the tsctl command * First steps toward adding the ability to manually run a sketch. * Revert "First steps toward adding the ability to manually run a sketch." This reverts commit * Adding a list sketch to tsctl.
[ { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -303,6 +303,34 @@ class SearchTemplateManager(Command):\ndb_session.commit()\n+class ListSketches(Command):\n+ \"\"\"List all available sketches.\"\"\"\n+\n+ # pylint: disable=arguments-differ, method-hidden\n+ def run(self):\n+ \"\"\"The run method for the command.\"\"\"\n+ sketches = Sketch.query.all()\n+\n+ name_len = max([len(x.name) for x in sketches])\n+ desc_len = max([len(x.description) for x in sketches])\n+\n+ if not name_len:\n+ name_len = 5\n+ if not desc_len:\n+ desc_len = 10\n+\n+ fmt_string = '{{0:^3d}} | {{1:{0:d}s}} | {{2:{1:d}s}}'.format(\n+ name_len, desc_len)\n+\n+ print('+-'*40)\n+ print(' ID | Name {0:s} | Description'.format(' '*(name_len-5)))\n+ print('+-'*40)\n+ for sketch in sketches:\n+ print(fmt_string.format(\n+ sketch.id, sketch.name, sketch.description))\n+ print('-'*80)\n+\n+\nclass ImportTimeline(Command):\n\"\"\"Create a new Timesketch timeline from a file.\"\"\"\noption_list = (\n@@ -431,6 +459,7 @@ def main():\nshell_manager.add_command('add_index', AddSearchIndex())\nshell_manager.add_command('db', MigrateCommand)\nshell_manager.add_command('drop_db', DropDataBaseTables())\n+ shell_manager.add_command('list_sketches', ListSketches())\nshell_manager.add_command('purge', PurgeTimeline())\nshell_manager.add_command('search_template', SearchTemplateManager())\nshell_manager.add_command('import', ImportTimeline())\n" } ]
Python
Apache License 2.0
google/timesketch
Adding list sketches to the tsctl command (#1002) * First steps toward adding the ability to manually run a sketch. * Revert "First steps toward adding the ability to manually run a sketch." This reverts commit c411329f6265ef73c9c277c56bd429c4ffd46ac0. * Adding a list sketch to tsctl.
263,133
23.10.2019 23:07:46
0
b85b5da403d63380e161cca135afe9da8daf8263
Initial stream uploader.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "from __future__ import unicode_literals\nimport json\n+import tempfile\nimport uuid\n# pylint: disable=wrong-import-order\n@@ -28,6 +29,11 @@ import pandas\nfrom .definitions import HTTP_STATUS_CODE_20X\n+def format_data_frame_row(row, format_message_string):\n+ \"\"\"Return a formatted data frame using a format string.\"\"\"\n+ return format_message_string.format(**row)\n+\n+\nclass TimesketchApi(object):\n\"\"\"Timesketch API object\n@@ -503,6 +509,100 @@ class Sketch(BaseResource):\nsearchindex=timeline['searchindex']['index_name'])\nreturn timeline_obj\n+ def upload_data_frame(\n+ self, data_frame, timeline_name, format_message_string=''):\n+ \"\"\"Upload a data frame to the server for indexing.\n+\n+ In order for a data frame to be uploaded to Timesketch it requires the\n+ following columns:\n+ + message\n+ + datetime\n+ + timestamp_desc\n+\n+ See more details here: https://github.com/google/timesketch/blob/\\\n+ master/docs/CreateTimelineFromJSONorCSV.md\n+\n+ Args:\n+ data_frame: the pandas dataframe object containing the data to\n+ upload.\n+ timeline_name: the name of the timeline in Timesketch.\n+ format_message_string: optional format string that will be used\n+ to generate a message column to the data frame. An example\n+ would be: '{src_ip:s} to {dst_ip:s}, {bytes:d} bytes\n+ transferred'. Each variable name in the format strings maps\n+ to column names in the data frame.\n+\n+ Returns:\n+ A string with the upload status.\n+\n+ Raises:\n+ ValueError: if the dataframe cannot be uploaded to Timesketch.\n+ \"\"\"\n+ if 'timestamp_desc' not in data_frame:\n+ data_frame['timestamp_desc'] = timeline_name\n+\n+ if 'message' not in data_frame:\n+ if not format_message_string:\n+ string_items = []\n+ for column in data_frame.columns:\n+ if 'time' in column:\n+ continue\n+ elif 'timestamp_desc' in column:\n+ continue\n+ string_items.append('{0:s} = {{0!s}}'.format(column))\n+ format_message_string = ' '.join(string_items)\n+\n+ data_frame['message'] = data_frame.apply(\n+ lambda row: format_data_frame_row(\n+ row, format_message_string), axis=1)\n+\n+ if 'datetime' not in data_frame:\n+ for column in data_frame.columns[\n+ data_frame.columns.str.contains('time')]:\n+ if column == 'timestamp_desc':\n+ continue\n+ data_frame['timestamp'] = pandas.to_datetime(\n+ data_frame[column], utc=True)\n+ data_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n+ '%Y-%m-%dT%H:%M:%S%z')\n+\n+ if not 'datetime' in data_frame:\n+ raise ValueError(\n+ 'Need a field called datetime in the data frame that is '\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+\n+ if not 'message' in data_frame:\n+ raise ValueError(\n+ 'Need a field called message in the data frame, use the '\n+ 'formatting string to generate one automatically.')\n+\n+ if not 'timestamp_desc' in data_frame:\n+ raise ValueError(\n+ 'Need a field called timestamp_desc in the data frame.')\n+\n+ # We don't want to include any columns that start with an underscore.\n+ columns = list(\n+ data_frame.columns[~data_frame.columns.str.contains('^_')])\n+ data_frame_use = data_frame[columns]\n+\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n+ result = self.upload(\n+ timeline_name=timeline_name, file_path=csv_file.name)\n+\n+ return_lines = []\n+ for timesketch_object in result.data.get('objects', []):\n+ return_lines.append('Timeline: {0:s}\\nStatus: {1:s}'.format(\n+ timesketch_object.get('description'),\n+ ','.join([x.get(\n+ 'status') for x in timesketch_object.get('status')])))\n+ return_lines.append('CSV file saved as: {0:s}'.format(csv_file.name))\n+\n+ return '\\n'.join(return_lines)\n+\ndef add_timeline(self, searchindex):\n\"\"\"Add timeline to sketch.\n@@ -1279,3 +1379,174 @@ class Timeline(BaseResource):\nindex_name = timeline['objects'][0]['searchindex']['index_name']\nself._searchindex = index_name\nreturn self._searchindex\n+\n+\n+class UploadStreamer(object):\n+ \"\"\"Upload object used to stream results to Timesketch.\"\"\"\n+\n+ # The number of entries before automatically flushing\n+ # the streamer.\n+ ENTRY_THRESHOLD = 10000\n+\n+ def __init__(self, entry_threshold=None):\n+ \"\"\"Initialize the upload streamer.\"\"\"\n+ self._count = 0\n+ self._data_lines = []\n+ self._format_string = None\n+ self._index = uuid.uuid4().hex\n+ self._resource_url = ''\n+ self._sketch = None\n+ self._timeline_id = None\n+ self._timeline_name = None\n+ self._timestamp_desc = None\n+\n+ if entry_threshold:\n+ self._threshold = entry_threshold\n+ else:\n+ self._threshold = self.ENTRY_THRESHOLD\n+\n+ def _ready(self):\n+ \"\"\"Check whether all variables have been set.\"\"\"\n+ if self._format_string is None:\n+ return False\n+\n+ if self._sketch is None:\n+ return False\n+\n+ if self._timestamp_desc is None:\n+ return False\n+\n+ return True\n+\n+ def _reset(self):\n+ \"\"\"Reset the buffer.\"\"\"\n+ self._count = 0\n+ self._data_lines = []\n+\n+ def add(self, entry):\n+ \"\"\"Add an entry into the buffer.\n+\n+ Args:\n+ entry: a dict object to add to the buffer.\n+\n+ Raises:\n+ TypeError: if the entry is not a dict.\n+ \"\"\"\n+ if not isinstance(entry, dict):\n+ raise TypeError('Entry object needs to be a dict.')\n+\n+ if self._count >= self._threshold:\n+ self.flush(end_stream=False)\n+ self._reset()\n+\n+ self._data_lines.append(entry)\n+ self._count += 1\n+\n+ def flush(self, end_stream=True):\n+ \"\"\"Flushes the buffer and uploads to timesketch.\n+\n+ Args:\n+ end_stream: boolean that determines whether this is the final\n+ data to be flushed or whether there is more to come.\n+\n+ Raises:\n+ ValueError: if the stream object is not fully configured.\n+ RuntimeError: if the stream was not uploaded.\n+ \"\"\"\n+ if not self._ready():\n+ raise ValueError(\n+ 'Need to fully configure object before uploading.')\n+\n+ data_frame = pandas.DataFrame(self._data_lines)\n+\n+ if 'message' not in data_frame:\n+ data_frame['message'] = data_frame.apply(\n+ lambda row: format_data_frame_row(\n+ row, self._format_string), axis=1)\n+ if 'timestamp_desc' not in data_frame:\n+ data_frame['timestamp_desc'] = self._timestamp_desc\n+\n+ if 'datetime' not in data_frame:\n+ for column in data_frame.columns[\n+ data_frame.columns.str.contains('time')]:\n+ if column == 'timestamp_desc':\n+ continue\n+ try:\n+ data_frame['timestamp'] = pandas.to_datetime(\n+ data_frame[column], utc=True)\n+ # We want the first successful timestamp value.\n+ break\n+ except ValueError:\n+ pass\n+ data_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n+ '%Y-%m-%dT%H:%M:%S%z')\n+\n+ # We don't want to include any columns that start with an underscore.\n+ columns = list(\n+ data_frame.columns[~data_frame.columns.str.contains('^_')])\n+ data_frame_use = data_frame[columns]\n+\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n+\n+ files = {'file': open(csv_file.name, 'rb')}\n+ data = {\n+ 'name': self._timeline_name,\n+ 'sketch_id': self._sketch.id,\n+ 'enable_stream': not end_stream,\n+ 'index_name': self._index,\n+ }\n+\n+ response = self._sketch.api.session.post(\n+ self._resource_url, files=files, data=data)\n+\n+ if response.status_code not in HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Error uploading data: {0:s}, file: {1:s}, index {2:s}'.format(\n+ response.reason, csv_file.name, self._index))\n+\n+ response_dict = response.json()\n+ self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n+\n+ def set_sketch(self, sketch):\n+ \"\"\"Set a client for the streamer.\n+\n+ Args:\n+ sketch: an instance of Sketch that is used to communicate\n+ with the API to upload data.\n+ \"\"\"\n+ self._sketch = sketch\n+ self._resource_url = '{0:s}/upload/'.format(sketch.api.api_root)\n+\n+ def set_format_string(self, format_string):\n+ \"\"\"Set the message format string.\"\"\"\n+ self._format_string = format_string\n+\n+ def set_timeline_name(self, name):\n+ \"\"\"Set the timeline name.\"\"\"\n+ self._timeline_name = name\n+\n+ def set_timestamp_description(self, description):\n+ \"\"\"Set the timestamp description field.\"\"\"\n+ self._timestamp_desc = description\n+\n+ @property\n+ def timeline(self):\n+ \"\"\"Returns a timeline object.\"\"\"\n+ timeline_obj = Timeline(\n+ timeline_id=self._timeline_id,\n+ sketch_id=self._sketch.id,\n+ api=self._sketch.api,\n+ name=self._timeline_name,\n+ searchindex=self._index_name)\n+ return timeline_obj\n+\n+ def __enter__(self):\n+ \"\"\"Make it possible to use \"with\" statement.\"\"\"\n+ self._reset()\n+ return self\n+\n+ # pylint: disable=unused-argument\n+ def __exit__(self, exception_type, exception_value, traceback):\n+ \"\"\"Make it possible to use \"with\" statement.\"\"\"\n+ self.flush(end_stream=True)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1407,7 +1407,7 @@ class UploadFileResource(ResourceMixin, Resource):\nif not isinstance(filename, six.text_type):\nfilename = codecs.decode(filename, 'utf-8')\n- index_name = uuid.uuid4().hex\n+ index_name = form.index_name.data or uuid.uuid4().hex\nif not isinstance(index_name, six.text_type):\nindex_name = codecs.decode(index_name, 'utf-8')\n@@ -1441,11 +1441,13 @@ class UploadFileResource(ResourceMixin, Resource):\ndb_session.add(timeline)\ndb_session.commit()\n+ stream = form.enable_stream.data\n# Start Celery pipeline for indexing and analysis.\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\npipeline = tasks.build_index_pipeline(\n- file_path, timeline_name, index_name, file_extension, sketch_id)\n+ file_path, timeline_name, index_name, file_extension, sketch_id,\n+ only_index=stream)\npipeline.apply_async()\n# Return Timeline if it was created.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/forms.py", "new_path": "timesketch/lib/forms.py", "diff": "@@ -256,6 +256,9 @@ class UploadFileForm(BaseForm):\n])\nname = StringField('Timeline name', validators=[Optional()])\nsketch_id = IntegerField('Sketch ID', validators=[Optional()])\n+ index_name = StringField('Index Name', validators=[Optional()])\n+ enable_stream = BooleanField(\n+ 'Enable stream', false_values={False, 'false', ''}, default=False)\nclass StoryForm(BaseForm):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -132,7 +132,7 @@ def _get_index_analyzers():\ndef build_index_pipeline(file_path, timeline_name, index_name, file_extension,\n- sketch_id=None):\n+ sketch_id=None, only_index=False):\n\"\"\"Build a pipeline for index and analysis.\nArgs:\n@@ -141,6 +141,10 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nindex_name: Name of the index to index to.\nfile_extension: The file extension of the file.\nsketch_id: The ID of the sketch to analyze.\n+ only_index: If set to true then only indexing tasks are run, not\n+ analyzers. This is to be used when uploading data in chunks,\n+ we don't want to run the analyzers until all chunks have been\n+ uploaded.\nReturns:\nCelery chain with indexing task (or single indexing task) and analyzer\n@@ -151,13 +155,16 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nsketch_analyzer_chain = None\nsearchindex = SearchIndex.query.filter_by(index_name=index_name).first()\n+ index_task = index_task_class.s(\n+ file_path, timeline_name, index_name, file_extension)\n+\n+ if only_index:\n+ return index_task\n+\nif sketch_id:\nsketch_analyzer_chain = build_sketch_analysis_pipeline(\nsketch_id, searchindex.id, user_id=None)\n- index_task = index_task_class.s(\n- file_path, timeline_name, index_name, file_extension)\n-\n# If there are no analyzers just run the indexer.\nif not index_analyzer_chain and not sketch_analyzer_chain:\nreturn index_task\n" } ]
Python
Apache License 2.0
google/timesketch
Initial stream uploader.
263,133
24.10.2019 09:27:31
0
a94406e5ebff014ea22f2d1f02056276cd686e63
Making some changes to the streamer.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "\"\"\"Timesketch API client.\"\"\"\nfrom __future__ import unicode_literals\n+import os\nimport json\nimport tempfile\nimport uuid\n@@ -509,6 +510,7 @@ class Sketch(BaseResource):\nsearchindex=timeline['searchindex']['index_name'])\nreturn timeline_obj\n+ # TODO: Change this function to use the upload streamer...\ndef upload_data_frame(\nself, data_frame, timeline_name, format_message_string=''):\n\"\"\"Upload a data frame to the server for indexing.\n@@ -1405,25 +1407,123 @@ class UploadStreamer(object):\nelse:\nself._threshold = self.ENTRY_THRESHOLD\n+ def _fix_data_frame(self, data_frame):\n+ \"\"\"Returns a data frame with added columns for Timesketch upload.\n+\n+ Args:\n+ data_frame: a pandas data frame.\n+\n+ Returns:\n+ A pandas data frame with added columns needed for Timesketch.\n+ \"\"\"\n+ if 'message' not in data_frame:\n+ data_frame['message'] = data_frame.apply(\n+ lambda row: format_data_frame_row(\n+ row, self._format_string), axis=1)\n+\n+ if 'timestamp_desc' not in data_frame:\n+ data_frame['timestamp_desc'] = self._timestamp_desc\n+\n+ if 'datetime' not in data_frame:\n+ for column in data_frame.columns[\n+ data_frame.columns.str.contains('time')]:\n+ if column == 'timestamp_desc':\n+ continue\n+ try:\n+ data_frame['timestamp'] = pandas.to_datetime(\n+ data_frame[column], utc=True)\n+ # We want the first successful timestamp value.\n+ break\n+ except ValueError:\n+ pass\n+ data_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n+ '%Y-%m-%dT%H:%M:%S%z')\n+\n+ # We don't want to include any columns that start with an underscore.\n+ columns = list(\n+ data_frame.columns[~data_frame.columns.str.contains('^_')])\n+ return data_frame[columns]\n+\ndef _ready(self):\n- \"\"\"Check whether all variables have been set.\"\"\"\n+ \"\"\"Check whether all variables have been set.\n+\n+ Raises:\n+ ValueError: if the streamer has not yet been fully configured.\n+ \"\"\"\nif self._format_string is None:\n- return False\n+ raise ValueError('Format string has not yet been set.')\nif self._sketch is None:\n- return False\n+ raise ValueError('Sketch has not yet been set.')\nif self._timestamp_desc is None:\n- return False\n-\n- return True\n+ raise ValueError('Timestamp description has not yet been set.')\ndef _reset(self):\n\"\"\"Reset the buffer.\"\"\"\nself._count = 0\nself._data_lines = []\n- def add(self, entry):\n+ def _upload_data(self, file_name, end_stream):\n+ \"\"\"Upload data TODO ADD DOCSTRING.\"\"\"\n+ files = {\n+ 'file': open(file_name, 'rb')\n+ }\n+ data = {\n+ 'name': self._timeline_name,\n+ 'sketch_id': self._sketch.id,\n+ 'enable_stream': not end_stream,\n+ 'index_name': self._index,\n+ }\n+\n+ response = self._sketch.api.session.post(\n+ self._resource_url, files=files, data=data)\n+\n+ if response.status_code not in HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Error uploading data: {0:s}, file: {1:s}, index {2:s}'.format(\n+ response.reason, file_name, self._index))\n+\n+ response_dict = response.json()\n+ self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n+\n+ def add_dataframe(self, data_frame):\n+ \"\"\"Add a data frame into the buffer.\"\"\"\n+ self._ready()\n+\n+ if not isinstance(data_frame, pandas.DataFrame):\n+ raise TypeError('Entry object needs to be a DataFrame')\n+\n+ size = data_frame.shape[0]\n+ data_frame_use = self._fix_data_frame(data_frame)\n+\n+ if size < self._threshold:\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n+ self._upload_data(csv_file.name, end_stream=True)\n+ return\n+\n+ chunks = int(size / self._threshold)\n+ for index in range(0, chunks):\n+ chunk_start = index * chunks\n+ data_chunk = data_frame_use[\n+ chunk_start:chunk_start + self._threshold]\n+\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_chunk.to_csv(csv_file.name, index=False, encoding='utf-8')\n+\n+ end_stream = bool(index == chunks - 1)\n+ self._upload_data(csv_file.name, end_stream=end_stream)\n+\n+ def add_file(self, filepath):\n+ \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\"\"\"\n+ self._ready()\n+\n+ if not os.path.isfile(filepath):\n+ raise TypeError('Entry object needs to be a file that exists.')\n+ # TODO: implement.\n+\n+ def add_dict(self, entry):\n\"\"\"Add an entry into the buffer.\nArgs:\n@@ -1432,6 +1532,7 @@ class UploadStreamer(object):\nRaises:\nTypeError: if the entry is not a dict.\n\"\"\"\n+ self._ready()\nif not isinstance(entry, dict):\nraise TypeError('Entry object needs to be a dict.')\n@@ -1457,56 +1558,15 @@ class UploadStreamer(object):\nraise ValueError(\n'Need to fully configure object before uploading.')\n+ if not self._data_lines:\n+ return\ndata_frame = pandas.DataFrame(self._data_lines)\n-\n- if 'message' not in data_frame:\n- data_frame['message'] = data_frame.apply(\n- lambda row: format_data_frame_row(\n- row, self._format_string), axis=1)\n- if 'timestamp_desc' not in data_frame:\n- data_frame['timestamp_desc'] = self._timestamp_desc\n-\n- if 'datetime' not in data_frame:\n- for column in data_frame.columns[\n- data_frame.columns.str.contains('time')]:\n- if column == 'timestamp_desc':\n- continue\n- try:\n- data_frame['timestamp'] = pandas.to_datetime(\n- data_frame[column], utc=True)\n- # We want the first successful timestamp value.\n- break\n- except ValueError:\n- pass\n- data_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n- '%Y-%m-%dT%H:%M:%S%z')\n-\n- # We don't want to include any columns that start with an underscore.\n- columns = list(\n- data_frame.columns[~data_frame.columns.str.contains('^_')])\n- data_frame_use = data_frame[columns]\n+ data_frame_use = self._fix_data_frame(data_frame)\ncsv_file = tempfile.NamedTemporaryFile(suffix='.csv')\ndata_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n- files = {'file': open(csv_file.name, 'rb')}\n- data = {\n- 'name': self._timeline_name,\n- 'sketch_id': self._sketch.id,\n- 'enable_stream': not end_stream,\n- 'index_name': self._index,\n- }\n-\n- response = self._sketch.api.session.post(\n- self._resource_url, files=files, data=data)\n-\n- if response.status_code not in HTTP_STATUS_CODE_20X:\n- raise RuntimeError(\n- 'Error uploading data: {0:s}, file: {1:s}, index {2:s}'.format(\n- response.reason, csv_file.name, self._index))\n-\n- response_dict = response.json()\n- self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n+ self._upload_data(csv_file.name, end_stream=end_stream)\ndef set_sketch(self, sketch):\n\"\"\"Set a client for the streamer.\n" } ]
Python
Apache License 2.0
google/timesketch
Making some changes to the streamer.
263,096
24.10.2019 14:39:59
-7,200
90c8007be376ef20b7aa00a95038509b6e151633
Install documentation from plaso changed location has been moved to so the PR will reduce number of clicks needed to get to the docs by two.
[ { "change_type": "MODIFY", "old_path": "docs/CreateTimelineFromPlaso.md", "new_path": "docs/CreateTimelineFromPlaso.md", "diff": "# Create timeline from Plaso file\n-You need to run version >= 1.5.0 Plaso on your Timesketch server. See the [official Plaso documentation](https://github.com/log2timeline/plaso/wiki/Ubuntu-Packaged-Release) for installing Plaso and it's dependencies. If you haven't installed Timesketch yet, take a look at the [installation instructions](Installation.md).\n+You need to run version >= 1.5.0 Plaso on your Timesketch server. See the [official Plaso documentation](https://plaso.readthedocs.io/en/latest/sources/user/Users-Guide.html#installing-the-packaged-release) for installing Plaso and it's dependencies. If you haven't installed Timesketch yet, take a look at the [installation instructions](Installation.md).\nWhen you have working installations of Timesketch and Plaso you can, from the command line, do:\n" } ]
Python
Apache License 2.0
google/timesketch
Install documentation from plaso changed location https://github.com/log2timeline/plaso/wiki has been moved to https://plaso.readthedocs.io so the PR will reduce number of clicks needed to get to the docs by two.
263,133
24.10.2019 14:03:09
0
f9a98b0bafdd1172c7e5cf9b9697addb120cd883
Minor minor change
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -563,7 +563,7 @@ class Sketch(BaseResource):\nreturn 'No return value.'\nreturn_lines = []\n- for timesketch_object in response.data.get('objects', []):\n+ for timesketch_object in response.get('objects', []):\nreturn_lines.append('Timeline: {0:s}\\nStatus: {1:s}'.format(\ntimesketch_object.get('description'),\n','.join([x.get(\n" } ]
Python
Apache License 2.0
google/timesketch
Minor minor change
263,133
24.10.2019 14:30:41
0
04a1db2066ece1c7740e673f8ab03a992d1bcfff
First version of documentation and minor changes.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -28,6 +28,7 @@ Timesketch is an open source tool for collaborative forensic timeline analysis.\n* [Create timeline from JSON/JSONL/CSV file](docs/CreateTimelineFromJSONorCSV.md)\n* [Create timeline from Plaso file](docs/CreateTimelineFromPlaso.md)\n* [Enable Plaso upload via HTTP](docs/EnablePlasoUpload.md)\n+* [Use the API client to upload data](docs/UploadDataViaAPI.md)\n#### Using Timesketch\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -1393,8 +1393,8 @@ class UploadStreamer(object):\nif 'datetime' not in data_frame:\nfor column in data_frame.columns[\n- data_frame.columns.str.contains('time')]:\n- if column == 'timestamp_desc':\n+ data_frame.columns.str.contains('time', case=False)]:\n+ if column.lower() == 'timestamp_desc':\ncontinue\ntry:\ndata_frame['timestamp'] = pandas.to_datetime(\n@@ -1403,6 +1403,7 @@ class UploadStreamer(object):\nbreak\nexcept ValueError:\npass\n+ if 'timestamp' in data_frame:\ndata_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n'%Y-%m-%dT%H:%M:%S%z')\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/UploadDataViaAPI.md", "diff": "+# Create Timeline From Other Sources\n+\n+Not all data comes in a good [CSV or JSONL\n+format](docs/CreateTimelineFromJSONorCSV.md) that can be imported\n+directly into Timesketch. In those cases it might be beneficial\n+to have a separate importer in Timesketch that can deal with arbitrary data, for\n+instance if there is already a python library to parse the data, or the data can\n+be read in another format, such as a [pandas\n+DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html).\n+\n+Let's look at how to import data using the API client.\n+\n+## Pandas DataFrame\n+\n+DataFrames can be generated from multiple sources and methods. This\n+documentation is in no way, shape or form going to cover that in any sort of\n+details. There are plenty of guides that can be found online to help you there.\n+\n+Let's just look at a simple case.\n+\n+```\n+In [1]: import pandas as pd\n+\n+In [2]: frame = pd.read_excel('~/Documents/SomeRandomDocument.xlsx')\n+\n+In [3]: frame\n+Out[3]:\n+Timestamp What URL Results\n+0 2019-05-02 23:21:10 Something http://evil.com Nothing to see here\n+1 2019-05-22 12:12:45 Other http://notevil.com Move on\n+2 2019-06-23 02:00:12 Not really That http://totallylegit.com Let's not look,shall we\n+```\n+\n+Here we have a data frame that we may want to add to our Timesketch instance.\n+What is missing here are few of the necessary columns, see\n+[documentation]((docs/CreateTimelineFromJSONorCSV.md). We don't really need to\n+add them here, we can do that all in our upload stream. Let's start by\n+connecting to a Timesketch instance.\n+\n+```\n+import pandas as pd\n+\n+from timesketch_api_client import client\n+\n+...\n+def action():\n+ frame = pd.read_excel('~/Downloads/SomeRandomDocument.xlsx')\n+\n+ ts = client.TimesketchApi(SERVER_LOCATION, USERNAME, PASSWORD)\n+ my_sketch = ts.get_sketch(SKETCH_ID)\n+\n+ with client.UploadStreamer() as streamer:\n+ streamer.set_sketch(my_sketch)\n+ streamer.set_timestamp_description('Web Log')\n+ streamer.set_timeline_name('excel_import')\n+ streamer.set_message_format_string(\n+ '{What:s} resulted in {Results:s}, pointed from {URL:s}')\n+\n+ streamer.add_data_frame(frame)\n+```\n+\n" } ]
Python
Apache License 2.0
google/timesketch
First version of documentation and minor changes.
263,133
24.10.2019 15:30:13
0
c28382bf49098f0ac8af69c0445d1d535336a019
Adding an API to trigger analyzer pipeline run.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -1610,3 +1610,16 @@ class UploadStreamer(object):\ndef __exit__(self, exception_type, exception_value, traceback):\n\"\"\"Make it possible to use \"with\" statement.\"\"\"\nself.flush(end_stream=True)\n+\n+ try:\n+ self._ready()\n+ except ValueError:\n+ return\n+\n+ pipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\n+ self._sketch.api.api_root, self._sketch.id)\n+ data = {\n+ 'sketch_id': self._sketch.id,\n+ 'index_name': self._index_name\n+ }\n+ _ = self._sketch.api.session.post(pipe_resource, data=data)\n" }, { "change_type": "MODIFY", "old_path": "docs/UploadDataViaAPI.md", "new_path": "docs/UploadDataViaAPI.md", "diff": "@@ -59,3 +59,67 @@ def action():\nstreamer.add_data_frame(frame)\n```\n+Let's go over the functionality of the streamer a bit. A streamer is opened\n+using the `with` statement in Python, which returns back an object. Before you\n+can use the streamer you'll have to configure it:\n+\n+ + Add a sketch object to it, this will be the sketch used to upload the data\n+ to.\n+ + Set the `timestamp_desc` field using the\n+ `streamer.set_timestamp_description`. The content of this string will be used\n+ for the `timestamp_desc` field, if it doesn't already exist.\n+ + Set the name of the imported timeline.\n+ + Set a format message string. Timesketch expects one field, called `message`\n+ to exist. If it does not exist, a format message string needs to be defined\n+ that can be used to generate the messsage field. This is basically a python\n+ [formatting string](https://pyformat.info/) that uses the name of each column\n+ as a variable name, eg. `\"{src_ip:s} connected to {dst_ip:s}\"` means that the\n+ content in the column name `src_ip` will be formatted as a string and\n+ replaces the `{src_ip:s}` in the format string. So if you have a row that\n+ contains the variables: `src_ip = \"10.10.10.10\", dst_ip = \"8.8.8.8\"` then the\n+ message string will look like: `10.10.10.10 connected to 8.8.8.8`.\n+ + Call any of the `streamer.add_` functions to add data.\n+\n+ The data that can be added to the streamer are:\n+\n+ + Pandas DataFrame.\n+ + A CSV, JSONL or a Plaso file.\n+ + A dictionary, one for each row in the dataset.\n+\n+Let's take another example of how the streamer is used to add content using the\n+dictionary approach.\n+\n+```\n+...\n+from scapy import all as scapy_all\n+...\n+\n+packets = scapy_all.rdpcap(fh)\n+\n+with client.UploadStreamer() as streamer:\n+ streamer.set_sketch(my_sketch)\n+ streamer.set_timestamp_description('Network Log')\n+ streamer.set_timeline_name('pcap_test_log')\n+ streamer.set_message_format_string(\n+ '{src_ip:s}:{src_port:d}->{dst_ip:s}:{dst_port:d} =\n+ {url:s}')\n+\n+ for packet in packets:\n+ # do something here\n+ ...\n+ timestamp = datetime.datetime.utcfromtimestamp(packet.time)\n+ for k, v in iter(data.fields.items()):\n+ for url in URL_RE.findall(str(v)):\n+ url = url.strip()\n+ streamer.add_dict({\n+ 'time': timestamp,\n+ 'src_ip': packet.getlayer('IP').src,\n+ 'dst_ip': packet.getlayer('IP').dst,\n+ 'src_port': layer.sport,\n+ 'dst_port': layer.dport,\n+ 'url': url})\n+```\n+\n+The streamer will take as an input to `add_dict` a dictionary that can contain\n+arbitrary field names. These will then later be transformed into a DataFrame and\n+then uploaded to Timesketch.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -71,6 +71,7 @@ from timesketch.lib.emojis import get_emojis_as_dict\nfrom timesketch.lib.forms import AddTimelineSimpleForm\nfrom timesketch.lib.forms import AggregationExploreForm\nfrom timesketch.lib.forms import AggregationLegacyForm\n+from timesketch.lib.forms import AnalyzerPipelineForm\nfrom timesketch.lib.forms import CreateTimelineForm\nfrom timesketch.lib.forms import SaveAggregationForm\nfrom timesketch.lib.forms import SaveViewForm\n@@ -1368,6 +1369,40 @@ class EventAnnotationResource(ResourceMixin, Resource):\nannotations, status_code=HTTP_STATUS_CODE_CREATED)\n+class AnalyzerPipelineResource(ResourceMixin, Resource):\n+ \"\"\"Resource to start analyzer pipeline.\"\"\"\n+\n+ @login_required\n+ def post(self):\n+ \"\"\"Handles POST request to the resource.\n+\n+ Returns:\n+ A string with information on pipeline.\n+ \"\"\"\n+ print('RUNNING ANALYZERS')\n+ form = AnalyzerPipelineForm()\n+ if not form.validate_on_submit():\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to validate the input form.')\n+\n+ sketch_id = form.sketch_id.data\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access to sketch')\n+\n+ index_name = form.index_name.data\n+\n+ # Start Celery pipeline for indexing and analysis.\n+ # Import here to avoid circular imports.\n+ from timesketch.lib import tasks\n+ pipeline = tasks.build_sketch_analysis_pipeline(\n+ sketch_id, index_name, user_id=None)\n+ pipeline.apply_async()\n+\n+\nclass UploadFileResource(ResourceMixin, Resource):\n\"\"\"Resource that processes uploaded files.\"\"\"\n@@ -1408,12 +1443,24 @@ class UploadFileResource(ResourceMixin, Resource):\nfilename = codecs.decode(filename, 'utf-8')\nindex_name = form.index_name.data or uuid.uuid4().hex\n+ print('Index name is: {} [{}]'.format(index_name, form.index_name.data))\nif not isinstance(index_name, six.text_type):\nindex_name = codecs.decode(index_name, 'utf-8')\nfile_path = os.path.join(upload_folder, filename)\nfile_storage.save(file_path)\n+ # Check if search index already exists.\n+ instance = SearchIndex.query.filter_by(\n+ name=timeline_name,\n+ description=timeline_name,\n+ user=current_user,\n+ index_name=index_name).first()\n+\n+ if instance:\n+ print('INDEX ALREADY EXISTS, NOT CREATING A NEW ONE')\n+ else:\n+ print('NEED TO CREATE AN INDEX...')\n# Create the search index in the Timesketch database\nsearchindex = SearchIndex.get_or_create(\nname=timeline_name,\n@@ -1442,6 +1489,7 @@ class UploadFileResource(ResourceMixin, Resource):\ndb_session.commit()\nstream = form.enable_stream.data\n+ print('Stream data: {}'.format(stream))\n# Start Celery pipeline for indexing and analysis.\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/routes.py", "new_path": "timesketch/api/v1/routes.py", "diff": "@@ -20,6 +20,7 @@ from .resources import AggregationLegacyResource\nfrom .resources import AggregationExploreResource\nfrom .resources import AggregationResource\nfrom .resources import AnalyzerRunResource\n+from .resources import AnalyzerPipelineResource\nfrom .resources import ExploreResource\nfrom .resources import EventResource\nfrom .resources import EventAnnotationResource\n@@ -53,6 +54,7 @@ API_ROUTES = [\n(SketchListResource, '/sketches/'),\n(SketchResource, '/sketches/<int:sketch_id>/'),\n(AnalyzerRunResource, '/sketches/<int:sketch_id>/analyzer/'),\n+ (AnalyzerPipelineResource, '/sketches/<int:sketch_id>/analyzer/auto_run/'),\n(AggregationListResource, '/sketches/<int:sketch_id>/aggregation/'),\n(AggregationLegacyResource, '/sketches/<int:sketch_id>/aggregation/legacy/'),\n(AggregationExploreResource, '/sketches/<int:sketch_id>/aggregation/explore/'),\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/forms.py", "new_path": "timesketch/lib/forms.py", "diff": "@@ -245,6 +245,12 @@ class EventAnnotationForm(BaseForm):\nevents = StringField('Events', validators=[DataRequired()])\n+class AnalyzerPipelineForm(BaseForm):\n+ \"\"\"Form to start analyzer pipeline.\"\"\"\n+ sketch_id = IntegerField('Sketch ID', validators=[Optional()])\n+ index_name = StringField('Index Name', validators=[Optional()])\n+\n+\nclass UploadFileForm(BaseForm):\n\"\"\"Form to handle file uploads.\"\"\"\nfile = FileField(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -159,7 +159,9 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nfile_path, timeline_name, index_name, file_extension)\nif only_index:\n+ print('ONLY INDEXING, NO ANALYZERS')\nreturn index_task\n+ print('We are about to get to the analyzers...')\nif sketch_id:\nsketch_analyzer_chain = build_sketch_analysis_pipeline(\n" } ]
Python
Apache License 2.0
google/timesketch
Adding an API to trigger analyzer pipeline run.
263,133
24.10.2019 15:43:05
0
7faf4b53927bbdd039945a9a2fa835fa6de76643
minor change to aPI
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -1619,7 +1619,6 @@ class UploadStreamer(object):\npipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\nself._sketch.api.api_root, self._sketch.id)\ndata = {\n- 'sketch_id': self._sketch.id,\n'index_name': self._index\n}\n_ = self._sketch.api.session.post(pipe_resource, data=data)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1373,7 +1373,7 @@ class AnalyzerPipelineResource(ResourceMixin, Resource):\n\"\"\"Resource to start analyzer pipeline.\"\"\"\n@login_required\n- def post(self):\n+ def post(self, sketch_id):\n\"\"\"Handles POST request to the resource.\nReturns:\n@@ -1386,7 +1386,6 @@ class AnalyzerPipelineResource(ResourceMixin, Resource):\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to validate the input form.')\n- sketch_id = form.sketch_id.data\nsketch = Sketch.query.get_with_acl(sketch_id)\nif not sketch.has_permission(current_user, 'write'):\nabort(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/forms.py", "new_path": "timesketch/lib/forms.py", "diff": "@@ -247,7 +247,6 @@ class EventAnnotationForm(BaseForm):\nclass AnalyzerPipelineForm(BaseForm):\n\"\"\"Form to start analyzer pipeline.\"\"\"\n- sketch_id = IntegerField('Sketch ID', validators=[Optional()])\nindex_name = StringField('Index Name', validators=[Optional()])\n" } ]
Python
Apache License 2.0
google/timesketch
minor change to aPI
263,133
25.10.2019 09:36:24
0
86fcd85042f888d7ce8f7da891a2b651c841d74c
Moving the uploader to a separate file.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -30,11 +30,6 @@ import pandas\nfrom .definitions import HTTP_STATUS_CODE_20X\n-def format_data_frame_row(row, format_message_string):\n- \"\"\"Return a formatted data frame using a format string.\"\"\"\n- return format_message_string.format(**row)\n-\n-\nclass TimesketchApi(object):\n\"\"\"Timesketch API object\n@@ -1347,278 +1342,3 @@ class Timeline(BaseResource):\nindex_name = timeline['objects'][0]['searchindex']['index_name']\nself._searchindex = index_name\nreturn self._searchindex\n-\n-\n-class UploadStreamer(object):\n- \"\"\"Upload object used to stream results to Timesketch.\"\"\"\n-\n- # The number of entries before automatically flushing\n- # the streamer.\n- ENTRY_THRESHOLD = 10000\n-\n- def __init__(self, entry_threshold=None):\n- \"\"\"Initialize the upload streamer.\"\"\"\n- self._count = 0\n- self._data_lines = []\n- self._format_string = None\n- self._index = uuid.uuid4().hex\n- self._last_response = None\n- self._resource_url = ''\n- self._sketch = None\n- self._timeline_id = None\n- self._timeline_name = None\n- self._timestamp_desc = None\n-\n- if entry_threshold:\n- self._threshold = entry_threshold\n- else:\n- self._threshold = self.ENTRY_THRESHOLD\n-\n- def _fix_data_frame(self, data_frame):\n- \"\"\"Returns a data frame with added columns for Timesketch upload.\n-\n- Args:\n- data_frame: a pandas data frame.\n-\n- Returns:\n- A pandas data frame with added columns needed for Timesketch.\n- \"\"\"\n- if 'message' not in data_frame:\n- data_frame['message'] = data_frame.apply(\n- lambda row: format_data_frame_row(\n- row, self._format_string), axis=1)\n-\n- if 'timestamp_desc' not in data_frame:\n- data_frame['timestamp_desc'] = self._timestamp_desc\n-\n- if 'datetime' not in data_frame:\n- for column in data_frame.columns[\n- data_frame.columns.str.contains('time', case=False)]:\n- if column.lower() == 'timestamp_desc':\n- continue\n- try:\n- data_frame['timestamp'] = pandas.to_datetime(\n- data_frame[column], utc=True)\n- # We want the first successful timestamp value.\n- break\n- except ValueError:\n- pass\n- if 'timestamp' in data_frame:\n- data_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n- '%Y-%m-%dT%H:%M:%S%z')\n-\n- # We don't want to include any columns that start with an underscore.\n- columns = list(\n- data_frame.columns[~data_frame.columns.str.contains('^_')])\n- return data_frame[columns]\n-\n- def _ready(self):\n- \"\"\"Check whether all variables have been set.\n-\n- Raises:\n- ValueError: if the streamer has not yet been fully configured.\n- \"\"\"\n- if self._format_string is None:\n- raise ValueError('Format string has not yet been set.')\n-\n- if self._sketch is None:\n- raise ValueError('Sketch has not yet been set.')\n-\n- if self._timestamp_desc is None:\n- raise ValueError('Timestamp description has not yet been set.')\n-\n- def _reset(self):\n- \"\"\"Reset the buffer.\"\"\"\n- self._count = 0\n- self._data_lines = []\n-\n- def _upload_data(self, file_name, end_stream):\n- \"\"\"Upload data TODO ADD DOCSTRING.\"\"\"\n- files = {\n- 'file': open(file_name, 'rb')\n- }\n- data = {\n- 'name': self._timeline_name,\n- 'sketch_id': self._sketch.id,\n- 'enable_stream': not end_stream,\n- 'index_name': self._index,\n- }\n-\n- response = self._sketch.api.session.post(\n- self._resource_url, files=files, data=data)\n-\n- if response.status_code not in HTTP_STATUS_CODE_20X:\n- raise RuntimeError(\n- 'Error uploading data: [{0:d}] {1:s} {2:s}, file: {3:s}, '\n- 'index {4:s}'.format(\n- response.status_code, response.reason, response.text,\n- file_name, self._index))\n-\n- response_dict = response.json()\n- self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n- self._last_response = response_dict\n-\n- def add_data_frame(self, data_frame):\n- \"\"\"Add a data frame into the buffer.\n-\n- Args:\n- data_frame: a pandas data frame object to add to the buffer.\n-\n- Raises:\n- ValueError: if the data frame does not contain the correct\n- columns for Timesketch upload.\n- \"\"\"\n- self._ready()\n-\n- if not isinstance(data_frame, pandas.DataFrame):\n- raise TypeError('Entry object needs to be a DataFrame')\n-\n- size = data_frame.shape[0]\n- data_frame_use = self._fix_data_frame(data_frame)\n-\n- if not 'datetime' in data_frame_use:\n- raise ValueError(\n- 'Need a field called datetime in the data frame that is '\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-\n- if not 'message' in data_frame_use:\n- raise ValueError(\n- 'Need a field called message in the data frame, use the '\n- 'formatting string to generate one automatically.')\n-\n- if not 'timestamp_desc' in data_frame_use:\n- raise ValueError(\n- 'Need a field called timestamp_desc in the data frame.')\n-\n- if size < self._threshold:\n- csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n- data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n- self._upload_data(csv_file.name, end_stream=True)\n- return\n-\n- chunks = int(size / self._threshold)\n- for index in range(0, chunks):\n- chunk_start = index * chunks\n- data_chunk = data_frame_use[\n- chunk_start:chunk_start + self._threshold]\n-\n- csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n- data_chunk.to_csv(csv_file.name, index=False, encoding='utf-8')\n-\n- end_stream = bool(index == chunks - 1)\n- self._upload_data(csv_file.name, end_stream=end_stream)\n-\n- def add_file(self, filepath):\n- \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\"\"\"\n- self._ready()\n-\n- if not os.path.isfile(filepath):\n- raise TypeError('Entry object needs to be a file that exists.')\n- # TODO: implement.\n-\n- def add_dict(self, entry):\n- \"\"\"Add an entry into the buffer.\n-\n- Args:\n- entry: a dict object to add to the buffer.\n-\n- Raises:\n- TypeError: if the entry is not a dict.\n- \"\"\"\n- self._ready()\n- if not isinstance(entry, dict):\n- raise TypeError('Entry object needs to be a dict.')\n-\n- if self._count >= self._threshold:\n- self.flush(end_stream=False)\n- self._reset()\n-\n- self._data_lines.append(entry)\n- self._count += 1\n-\n- def flush(self, end_stream=True):\n- \"\"\"Flushes the buffer and uploads to timesketch.\n-\n- Args:\n- end_stream: boolean that determines whether this is the final\n- data to be flushed or whether there is more to come.\n-\n- Raises:\n- ValueError: if the stream object is not fully configured.\n- RuntimeError: if the stream was not uploaded.\n- \"\"\"\n- if not self._data_lines:\n- return\n-\n- self._ready()\n-\n- data_frame = pandas.DataFrame(self._data_lines)\n- data_frame_use = self._fix_data_frame(data_frame)\n-\n- csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n- data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n-\n- self._upload_data(csv_file.name, end_stream=end_stream)\n-\n- @property\n- def response(self):\n- \"\"\"Returns the last response from an upload.\"\"\"\n- return self._last_response\n-\n- def set_sketch(self, sketch):\n- \"\"\"Set a client for the streamer.\n-\n- Args:\n- sketch: an instance of Sketch that is used to communicate\n- with the API to upload data.\n- \"\"\"\n- self._sketch = sketch\n- self._resource_url = '{0:s}/upload/'.format(sketch.api.api_root)\n-\n- def set_message_format_string(self, format_string):\n- \"\"\"Set the message format string.\"\"\"\n- self._format_string = format_string\n-\n- def set_timeline_name(self, name):\n- \"\"\"Set the timeline name.\"\"\"\n- self._timeline_name = name\n-\n- def set_timestamp_description(self, description):\n- \"\"\"Set the timestamp description field.\"\"\"\n- self._timestamp_desc = description\n-\n- @property\n- def timeline(self):\n- \"\"\"Returns a timeline object.\"\"\"\n- timeline_obj = Timeline(\n- timeline_id=self._timeline_id,\n- sketch_id=self._sketch.id,\n- api=self._sketch.api,\n- name=self._timeline_name,\n- searchindex=self._index)\n- return timeline_obj\n-\n- def __enter__(self):\n- \"\"\"Make it possible to use \"with\" statement.\"\"\"\n- self._reset()\n- return self\n-\n- # pylint: disable=unused-argument\n- def __exit__(self, exception_type, exception_value, traceback):\n- \"\"\"Make it possible to use \"with\" statement.\"\"\"\n- self.flush(end_stream=True)\n-\n- try:\n- self._ready()\n- except ValueError:\n- return\n-\n- pipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\n- self._sketch.api.api_root, self._sketch.id)\n- data = {\n- 'index_name': self._index\n- }\n- _ = self._sketch.api.session.post(pipe_resource, data=data)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "+# Copyright 2017 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch data importer.\"\"\"\n+from __future__ import unicode_literals\n+\n+import os\n+import tempfile\n+import uuid\n+\n+import pandas\n+from .definitions import HTTP_STATUS_CODE_20X\n+\n+\n+def format_data_frame_row(row, format_message_string):\n+ \"\"\"Return a formatted data frame using a format string.\"\"\"\n+ return format_message_string.format(**row)\n+\n+\n+class UploadStreamer(object):\n+ \"\"\"Upload object used to stream results to Timesketch.\"\"\"\n+\n+ # The number of entries before automatically flushing\n+ # the streamer.\n+ ENTRY_THRESHOLD = 10000\n+\n+ def __init__(self, entry_threshold=None):\n+ \"\"\"Initialize the upload streamer.\"\"\"\n+ self._count = 0\n+ self._data_lines = []\n+ self._format_string = None\n+ self._index = uuid.uuid4().hex\n+ self._last_response = None\n+ self._resource_url = ''\n+ self._sketch = None\n+ self._timeline_id = None\n+ self._timeline_name = None\n+ self._timestamp_desc = None\n+\n+ if entry_threshold:\n+ self._threshold = entry_threshold\n+ else:\n+ self._threshold = self.ENTRY_THRESHOLD\n+\n+ def _fix_data_frame(self, data_frame):\n+ \"\"\"Returns a data frame with added columns for Timesketch upload.\n+\n+ Args:\n+ data_frame: a pandas data frame.\n+\n+ Returns:\n+ A pandas data frame with added columns needed for Timesketch.\n+ \"\"\"\n+ if 'message' not in data_frame:\n+ data_frame['message'] = data_frame.apply(\n+ lambda row: format_data_frame_row(\n+ row, self._format_string), axis=1)\n+\n+ if 'timestamp_desc' not in data_frame:\n+ data_frame['timestamp_desc'] = self._timestamp_desc\n+\n+ if 'datetime' not in data_frame:\n+ for column in data_frame.columns[\n+ data_frame.columns.str.contains('time', case=False)]:\n+ if column.lower() == 'timestamp_desc':\n+ continue\n+ try:\n+ data_frame['timestamp'] = pandas.to_datetime(\n+ data_frame[column], utc=True)\n+ # We want the first successful timestamp value.\n+ break\n+ except ValueError:\n+ pass\n+ if 'timestamp' in data_frame:\n+ data_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n+ '%Y-%m-%dT%H:%M:%S%z')\n+\n+ # We don't want to include any columns that start with an underscore.\n+ columns = list(\n+ data_frame.columns[~data_frame.columns.str.contains('^_')])\n+ return data_frame[columns]\n+\n+ def _ready(self):\n+ \"\"\"Check whether all variables have been set.\n+\n+ Raises:\n+ ValueError: if the streamer has not yet been fully configured.\n+ \"\"\"\n+ if self._format_string is None:\n+ raise ValueError('Format string has not yet been set.')\n+\n+ if self._sketch is None:\n+ raise ValueError('Sketch has not yet been set.')\n+\n+ if self._timestamp_desc is None:\n+ raise ValueError('Timestamp description has not yet been set.')\n+\n+ def _reset(self):\n+ \"\"\"Reset the buffer.\"\"\"\n+ self._count = 0\n+ self._data_lines = []\n+\n+ def _upload_data(self, file_name, end_stream):\n+ \"\"\"Upload data TODO ADD DOCSTRING.\"\"\"\n+ files = {\n+ 'file': open(file_name, 'rb')\n+ }\n+ data = {\n+ 'name': self._timeline_name,\n+ 'sketch_id': self._sketch.id,\n+ 'enable_stream': not end_stream,\n+ 'index_name': self._index,\n+ }\n+\n+ response = self._sketch.api.session.post(\n+ self._resource_url, files=files, data=data)\n+\n+ if response.status_code not in HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Error uploading data: [{0:d}] {1:s} {2:s}, file: {3:s}, '\n+ 'index {4:s}'.format(\n+ response.status_code, response.reason, response.text,\n+ file_name, self._index))\n+\n+ response_dict = response.json()\n+ self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n+ self._last_response = response_dict\n+\n+ def add_data_frame(self, data_frame):\n+ \"\"\"Add a data frame into the buffer.\n+\n+ Args:\n+ data_frame: a pandas data frame object to add to the buffer.\n+\n+ Raises:\n+ ValueError: if the data frame does not contain the correct\n+ columns for Timesketch upload.\n+ \"\"\"\n+ self._ready()\n+\n+ if not isinstance(data_frame, pandas.DataFrame):\n+ raise TypeError('Entry object needs to be a DataFrame')\n+\n+ size = data_frame.shape[0]\n+ data_frame_use = self._fix_data_frame(data_frame)\n+\n+ if not 'datetime' in data_frame_use:\n+ raise ValueError(\n+ 'Need a field called datetime in the data frame that is '\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+\n+ if not 'message' in data_frame_use:\n+ raise ValueError(\n+ 'Need a field called message in the data frame, use the '\n+ 'formatting string to generate one automatically.')\n+\n+ if not 'timestamp_desc' in data_frame_use:\n+ raise ValueError(\n+ 'Need a field called timestamp_desc in the data frame.')\n+\n+ if size < self._threshold:\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n+ self._upload_data(csv_file.name, end_stream=True)\n+ return\n+\n+ chunks = int(size / self._threshold)\n+ for index in range(0, chunks):\n+ chunk_start = index * chunks\n+ data_chunk = data_frame_use[\n+ chunk_start:chunk_start + self._threshold]\n+\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_chunk.to_csv(csv_file.name, index=False, encoding='utf-8')\n+\n+ end_stream = bool(index == chunks - 1)\n+ self._upload_data(csv_file.name, end_stream=end_stream)\n+\n+ def add_file(self, filepath):\n+ \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\"\"\"\n+ self._ready()\n+\n+ if not os.path.isfile(filepath):\n+ raise TypeError('Entry object needs to be a file that exists.')\n+ # TODO: implement.\n+\n+ def add_dict(self, entry):\n+ \"\"\"Add an entry into the buffer.\n+\n+ Args:\n+ entry: a dict object to add to the buffer.\n+\n+ Raises:\n+ TypeError: if the entry is not a dict.\n+ \"\"\"\n+ self._ready()\n+ if not isinstance(entry, dict):\n+ raise TypeError('Entry object needs to be a dict.')\n+\n+ if self._count >= self._threshold:\n+ self.flush(end_stream=False)\n+ self._reset()\n+\n+ self._data_lines.append(entry)\n+ self._count += 1\n+\n+ def flush(self, end_stream=True):\n+ \"\"\"Flushes the buffer and uploads to timesketch.\n+\n+ Args:\n+ end_stream: boolean that determines whether this is the final\n+ data to be flushed or whether there is more to come.\n+\n+ Raises:\n+ ValueError: if the stream object is not fully configured.\n+ RuntimeError: if the stream was not uploaded.\n+ \"\"\"\n+ if not self._data_lines:\n+ return\n+\n+ self._ready()\n+\n+ data_frame = pandas.DataFrame(self._data_lines)\n+ data_frame_use = self._fix_data_frame(data_frame)\n+\n+ csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n+ data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n+\n+ self._upload_data(csv_file.name, end_stream=end_stream)\n+\n+ @property\n+ def response(self):\n+ \"\"\"Returns the last response from an upload.\"\"\"\n+ return self._last_response\n+\n+ def set_sketch(self, sketch):\n+ \"\"\"Set a client for the streamer.\n+\n+ Args:\n+ sketch: an instance of Sketch that is used to communicate\n+ with the API to upload data.\n+ \"\"\"\n+ self._sketch = sketch\n+ self._resource_url = '{0:s}/upload/'.format(sketch.api.api_root)\n+\n+ def set_message_format_string(self, format_string):\n+ \"\"\"Set the message format string.\"\"\"\n+ self._format_string = format_string\n+\n+ def set_timeline_name(self, name):\n+ \"\"\"Set the timeline name.\"\"\"\n+ self._timeline_name = name\n+\n+ def set_timestamp_description(self, description):\n+ \"\"\"Set the timestamp description field.\"\"\"\n+ self._timestamp_desc = description\n+\n+ @property\n+ def timeline(self):\n+ \"\"\"Returns a timeline object.\"\"\"\n+ timeline_obj = Timeline(\n+ timeline_id=self._timeline_id,\n+ sketch_id=self._sketch.id,\n+ api=self._sketch.api,\n+ name=self._timeline_name,\n+ searchindex=self._index)\n+ return timeline_obj\n+\n+ def __enter__(self):\n+ \"\"\"Make it possible to use \"with\" statement.\"\"\"\n+ self._reset()\n+ return self\n+\n+ # pylint: disable=unused-argument\n+ def __exit__(self, exception_type, exception_value, traceback):\n+ \"\"\"Make it possible to use \"with\" statement.\"\"\"\n+ self.flush(end_stream=True)\n+\n+ try:\n+ self._ready()\n+ except ValueError:\n+ return\n+\n+ pipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\n+ self._sketch.api.api_root, self._sketch.id)\n+ data = {\n+ 'index_name': self._index\n+ }\n+ _ = self._sketch.api.session.post(pipe_resource, data=data)\n" } ]
Python
Apache License 2.0
google/timesketch
Moving the uploader to a separate file.
263,133
25.10.2019 09:49:23
0
477912df0a6eefd3c6631f21a4a0684cfcb0be90
Making few changes.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "\"\"\"Timesketch API client.\"\"\"\nfrom __future__ import unicode_literals\n-import os\nimport json\n-import tempfile\nimport uuid\n# pylint: disable=wrong-import-order\n@@ -28,6 +26,7 @@ from requests.exceptions import ConnectionError\nimport altair\nimport pandas\nfrom .definitions import HTTP_STATUS_CODE_20X\n+from . import importer\nclass TimesketchApi(object):\n@@ -545,7 +544,7 @@ class Sketch(BaseResource):\nformat_message_string = ' '.join(string_items)\nresponse = None\n- with UploadStreamer() as streamer:\n+ with importer.ImportStreamer() as streamer:\nstreamer.set_sketch(self)\nstreamer.set_timeline_name(timeline_name)\nstreamer.set_timestamp_description('LOG')\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -19,6 +19,7 @@ import tempfile\nimport uuid\nimport pandas\n+from . import client\nfrom .definitions import HTTP_STATUS_CODE_20X\n@@ -27,7 +28,7 @@ def format_data_frame_row(row, format_message_string):\nreturn format_message_string.format(**row)\n-class UploadStreamer(object):\n+class ImportStreamer(object):\n\"\"\"Upload object used to stream results to Timesketch.\"\"\"\n# The number of entries before automatically flushing\n@@ -96,15 +97,9 @@ class UploadStreamer(object):\nRaises:\nValueError: if the streamer has not yet been fully configured.\n\"\"\"\n- if self._format_string is None:\n- raise ValueError('Format string has not yet been set.')\n-\nif self._sketch is None:\nraise ValueError('Sketch has not yet been set.')\n- if self._timestamp_desc is None:\n- raise ValueError('Timestamp description has not yet been set.')\n-\ndef _reset(self):\n\"\"\"Reset the buffer.\"\"\"\nself._count = 0\n@@ -195,7 +190,11 @@ class UploadStreamer(object):\nif not os.path.isfile(filepath):\nraise TypeError('Entry object needs to be a file that exists.')\n- # TODO: implement.\n+\n+ # TODO: Implement a buffer and split file up in chunks if it is larger\n+ # than the threshold.\n+ # TODO: Add a fix to files, to add fields.\n+ self._sketch.upload(self._timeline_name, filepath)\ndef add_dict(self, entry):\n\"\"\"Add an entry into the buffer.\n@@ -217,6 +216,20 @@ class UploadStreamer(object):\nself._data_lines.append(entry)\nself._count += 1\n+ def close(self):\n+ \"\"\"Close the streamer.\"\"\"\n+ try:\n+ self._ready()\n+ except ValueError:\n+ return\n+\n+ pipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\n+ self._sketch.api.api_root, self._sketch.id)\n+ data = {\n+ 'index_name': self._index\n+ }\n+ _ = self._sketch.api.session.post(pipe_resource, data=data)\n+\ndef flush(self, end_stream=True):\n\"\"\"Flushes the buffer and uploads to timesketch.\n@@ -271,7 +284,7 @@ class UploadStreamer(object):\n@property\ndef timeline(self):\n\"\"\"Returns a timeline object.\"\"\"\n- timeline_obj = Timeline(\n+ timeline_obj = client.Timeline(\ntimeline_id=self._timeline_id,\nsketch_id=self._sketch.id,\napi=self._sketch.api,\n@@ -288,15 +301,4 @@ class UploadStreamer(object):\ndef __exit__(self, exception_type, exception_value, traceback):\n\"\"\"Make it possible to use \"with\" statement.\"\"\"\nself.flush(end_stream=True)\n-\n- try:\n- self._ready()\n- except ValueError:\n- return\n-\n- pipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\n- self._sketch.api.api_root, self._sketch.id)\n- data = {\n- 'index_name': self._index\n- }\n- _ = self._sketch.api.session.post(pipe_resource, data=data)\n+ self.close()\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1402,7 +1402,6 @@ class AnalyzerPipelineResource(ResourceMixin, Resource):\n'There is no searchindex for index name: {0:s}'.format(\nindex_name))\n-\n# Start Celery pipeline for indexing and analysis.\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\n@@ -1448,6 +1447,7 @@ class UploadFileResource(ResourceMixin, Resource):\nif sketch_id:\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ print('WE BE DOING HTE UPLOADS')\n# We do not need a human readable filename or\n# datastore index name, so we use UUIDs here.\nfilename = uuid.uuid4().hex\n" } ]
Python
Apache License 2.0
google/timesketch
Making few changes.
263,133
25.10.2019 10:16:23
0
71dd2e7d67967bd628104c447d8c4c177bc48ebe
Updating documentation as well as adding a JSON importer.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "\"\"\"Timesketch data importer.\"\"\"\nfrom __future__ import unicode_literals\n+import json\nimport os\nimport tempfile\nimport uuid\n@@ -184,18 +185,6 @@ class ImportStreamer(object):\nend_stream = bool(index == chunks - 1)\nself._upload_data(csv_file.name, end_stream=end_stream)\n- def add_file(self, filepath):\n- \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\"\"\"\n- self._ready()\n-\n- if not os.path.isfile(filepath):\n- raise TypeError('Entry object needs to be a file that exists.')\n-\n- # TODO: Implement a buffer and split file up in chunks if it is larger\n- # than the threshold.\n- # TODO: Add a fix to files, to add fields.\n- self._sketch.upload(self._timeline_name, filepath)\n-\ndef add_dict(self, entry):\n\"\"\"Add an entry into the buffer.\n@@ -216,6 +205,54 @@ class ImportStreamer(object):\nself._data_lines.append(entry)\nself._count += 1\n+ def add_file(self, filepath):\n+ \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\"\"\"\n+ self._ready()\n+\n+ if not os.path.isfile(filepath):\n+ raise TypeError('Entry object needs to be a file that exists.')\n+\n+ # TODO: Implement a buffer and split file up in chunks if it is larger\n+ # than the threshold.\n+ # TODO: Add a fix to files, to add fields.\n+ self._sketch.upload(self._timeline_name, filepath)\n+\n+ def add_json(self, json_entry, column_names=None):\n+ \"\"\"Add an entry that is in a JSON format.\n+\n+ Args:\n+ json_entry: a single entry encoded in JSON.\n+ column_names: a list of column names if the JSON object\n+ is a list as an opposed to a dict.\n+\n+ Raises:\n+ TypeError: if the entry is not JSON or in the wrong JSON format.\n+ \"\"\"\n+ try:\n+ json_obj = json.loads(json_entry)\n+ except json.JSONDecodeError as e:\n+ raise TypeError('Data not as JSON, error: {0!s}'.format(e))\n+\n+ json_dict = {}\n+ if isinstance(json_obj, (list, tuple)):\n+ if not column_names:\n+ raise TypeError(\n+ 'Data is a list, but there are no defined column names.')\n+ if not len(json_obj) != len(column_names):\n+ raise TypeError(\n+ 'The number of columns ({0:d}) does not match the number '\n+ 'of columns in the JSON list ({1:d})'.format(\n+ len(column_names), len(json_obj)))\n+ json_dict = dict(zip(column_names, json_obj))\n+ elif isinstance(json_obj, dict):\n+ json_dict = json_obj\n+ else:\n+ raise TypeError(\n+ 'The JSON object needs to be either a dict or a list with '\n+ 'defined column names.')\n+\n+ self.add_dict(json_dict)\n+\ndef close(self):\n\"\"\"Close the streamer.\"\"\"\ntry:\n" }, { "change_type": "MODIFY", "old_path": "docs/UploadDataViaAPI.md", "new_path": "docs/UploadDataViaAPI.md", "diff": "Not all data comes in a good [CSV or JSONL\nformat](docs/CreateTimelineFromJSONorCSV.md) that can be imported\n-directly into Timesketch. In those cases it might be beneficial\n-to have a separate importer in Timesketch that can deal with arbitrary data, for\n-instance if there is already a python library to parse the data, or the data can\n-be read in another format, such as a [pandas\n+directly into Timesketch. Your data may lie in a SQL database, Excel sheet, or\n+even in CSV/JSON but it does not have the correct fields in it. In those cases\n+it might be beneficial to have a separate importer in Timesketch that can deal\n+with arbitrary data, for instance if there is already a python library to parse\n+the data, or the data can be read in another format, such as a [pandas\nDataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html).\n-Let's look at how to import data using the API client.\n+## Disclaimer\n+\n+A small disclaimer. Timesketch is not a parser, and does not intend to be a\n+parser. If you need to parse the data, you'll need other tools or libraries.\n+Parsers can be implemented using [plaso](https://github.com/log2timeline/plaso)\n+.\n+\n+\n+## What is the Importer Good For\n+\n+The Timesketch importer is to be used for data sources that you've already\n+parsed or have readily available, but they are not in the correct format that\n+Timesketch requires or you want an automatic way to import the data, or a way to\n+built an importer into your already existing toolsets.\n+\n+## Basics\n+\n+The importer will take as an input either:\n+\n+ + Pandas DataFrame.\n+ + CSV or JSONL.\n+ + JSON (one JSON per entry)\n+ + Python dict\n+\n+The best way to use the streamer is to by using the the `with` statement in\n+Python, which returns back an object. Before you can use the streamer you'll\n+have to configure it:\n+\n+ + Add a sketch object to it, this will be the sketch used to upload the data\n+ to.\n+ + Set the name of the imported timeline.\n+ + If the data does not contain a timestamp description you'll need to set the\n+ `timestamp_desc` field using the `streamer.set_timestamp_description`.\n+ The content of this string will be used for the `timestamp_desc` field,\n+ if it doesn't already exist.\n+ + If the data does not contain a column called `message` a format string can\n+ be supplied to automatically generate one. This is basically a python\n+ [formatting string](https://pyformat.info/) that uses the name of each column\n+ as a variable name, eg. `\"{src_ip:s} connected to {dst_ip:s}\"` means that the\n+ content in the column name `src_ip` will be formatted as a string and\n+ replaces the `{src_ip:s}` in the format string. So if you have a row that\n+ contains the variables: `src_ip = \"10.10.10.10\", dst_ip = \"8.8.8.8\"` then the\n+ message string will look like: `10.10.10.10 connected to 8.8.8.8`.\n+\n+The reason why the `with` statement is preferred is that it ensures that the\n+streamer gets properly closed at the end. The streamer can be used without\n+the `with` statement, however the developer is then required to make sure that\n+the streamer's `.close()` function is called at the end.\n+\n+Once the streamer is configured it can be used by calling any of the\n+`streamer.add_` functions to add data.\n+\n+Let's look at how to import data using the importer, using each of these data\n+sources.\n## Pandas DataFrame\n@@ -41,6 +95,7 @@ connecting to a Timesketch instance.\nimport pandas as pd\nfrom timesketch_api_client import client\n+from timesketch_api_client import importer\n...\ndef action():\n@@ -49,7 +104,7 @@ def action():\nts = client.TimesketchApi(SERVER_LOCATION, USERNAME, PASSWORD)\nmy_sketch = ts.get_sketch(SKETCH_ID)\n- with client.UploadStreamer() as streamer:\n+ with importer.ImportStreamer() as streamer:\nstreamer.set_sketch(my_sketch)\nstreamer.set_timestamp_description('Web Log')\nstreamer.set_timeline_name('excel_import')\n@@ -59,36 +114,14 @@ def action():\nstreamer.add_data_frame(frame)\n```\n-Let's go over the functionality of the streamer a bit. A streamer is opened\n-using the `with` statement in Python, which returns back an object. Before you\n-can use the streamer you'll have to configure it:\n-\n- + Add a sketch object to it, this will be the sketch used to upload the data\n- to.\n- + Set the `timestamp_desc` field using the\n- `streamer.set_timestamp_description`. The content of this string will be used\n- for the `timestamp_desc` field, if it doesn't already exist.\n- + Set the name of the imported timeline.\n- + Set a format message string. Timesketch expects one field, called `message`\n- to exist. If it does not exist, a format message string needs to be defined\n- that can be used to generate the messsage field. This is basically a python\n- [formatting string](https://pyformat.info/) that uses the name of each column\n- as a variable name, eg. `\"{src_ip:s} connected to {dst_ip:s}\"` means that the\n- content in the column name `src_ip` will be formatted as a string and\n- replaces the `{src_ip:s}` in the format string. So if you have a row that\n- contains the variables: `src_ip = \"10.10.10.10\", dst_ip = \"8.8.8.8\"` then the\n- message string will look like: `10.10.10.10 connected to 8.8.8.8`.\n- + Call any of the `streamer.add_` functions to add data.\n-\n- The data that can be added to the streamer are:\n+## Python Dict\n- + Pandas DataFrame.\n- + A CSV, JSONL or a Plaso file.\n- + A dictionary, one for each row in the dataset.\n-\n-Let's take another example of how the streamer is used to add content using the\n+Here is an example of how the streamer can be used to add content using the\ndictionary approach.\n+Here we use an external library, scapy, to read a PCAP file and import the data\n+from the network traffic to Timesketch.\n+\n```\n...\nfrom scapy import all as scapy_all\n@@ -96,7 +129,7 @@ from scapy import all as scapy_all\npackets = scapy_all.rdpcap(fh)\n-with client.UploadStreamer() as streamer:\n+with importer.ImportStreamer() as streamer:\nstreamer.set_sketch(my_sketch)\nstreamer.set_timestamp_description('Network Log')\nstreamer.set_timeline_name('pcap_test_log')\n@@ -123,3 +156,22 @@ with client.UploadStreamer() as streamer:\nThe streamer will take as an input to `add_dict` a dictionary that can contain\narbitrary field names. These will then later be transformed into a DataFrame and\nthen uploaded to Timesketch.\n+\n+## JSON\n+\n+Adding a JSON entry is identicial to the dict method, except that the each\n+entry is stored as a separate JSON object (one entry is only a single line).\n+\n+Let's look at an example:\n+\n+```\n+# TODO: Add an example.\n+\n+```\n+\n+\n+## CSV or JSONL file.\n+\n+```\n+#TODO: Add an example here.\n+```\n" } ]
Python
Apache License 2.0
google/timesketch
Updating documentation as well as adding a JSON importer.
263,133
25.10.2019 14:51:52
0
84e0c0ad40fe2dd30fc010432db1835e177dba31
Improving the file import
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -107,7 +107,13 @@ class ImportStreamer(object):\nself._data_lines = []\ndef _upload_data(self, file_name, end_stream):\n- \"\"\"Upload data TODO ADD DOCSTRING.\"\"\"\n+ \"\"\"Upload data to Timesketch.\n+\n+ Args:\n+ file_name: a full path to the file that is about to be uploaded.\n+ end_stream: boolean indicating whether this is the last chunk of\n+ the stream.\n+ \"\"\"\nfiles = {\n'file': open(file_name, 'rb')\n}\n@@ -205,17 +211,41 @@ class ImportStreamer(object):\nself._data_lines.append(entry)\nself._count += 1\n- def add_file(self, filepath):\n- \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\"\"\"\n+ def add_file(self, filepath, delimiter=','):\n+ \"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\n+\n+ Args:\n+ filepath: the path to the file to add.\n+ delimiter: if this is a CSV file then a delimiter can be defined.\n+\n+ Raises:\n+ TypeError: if the entry does not fulfill requirements.\n+ \"\"\"\nself._ready()\nif not os.path.isfile(filepath):\nraise TypeError('Entry object needs to be a file that exists.')\n- # TODO: Implement a buffer and split file up in chunks if it is larger\n- # than the threshold.\n- # TODO: Add a fix to files, to add fields.\n+ file_ending = filepath.lower().split('.')[-1]\n+ if file_ending == 'csv':\n+ data_frame = pandas.read_csv(filepath, delimiter=delimiter)\n+ self.add_data_frame(data_frame)\n+ elif file_ending == 'plaso':\nself._sketch.upload(self._timeline_name, filepath)\n+ elif file_ending == 'jsonl':\n+ data_frame = None\n+ with open(filepath, 'r') as fh:\n+ lines = [json.loads(x) for x in fh]\n+ data_frame= pandas.DataFrame(lines)\n+ if data_frame is None:\n+ raise TypeError('Unable to parse the JSON file.')\n+ if data_frame.empty:\n+ raise TypeError('Is the JSON file empty?')\n+\n+ self.add_data_frame(data_frame)\n+\n+ raise TypeError(\n+ 'File needs to have a file extension of: .csv, .jsonl or .plaso')\ndef add_json(self, json_entry, column_names=None):\n\"\"\"Add an entry that is in a JSON format.\n" } ]
Python
Apache License 2.0
google/timesketch
Improving the file import
263,133
25.10.2019 15:06:54
0
24aad814db44e77d5c52c38f0b71f8540ba7b5c9
Adding an excel read method.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -211,6 +211,34 @@ class ImportStreamer(object):\nself._data_lines.append(entry)\nself._count += 1\n+ def add_excel_file(self, filepath, sheet_name=0):\n+ \"\"\"Add a Microsoft Excel sheet to importer.\n+\n+ Args:\n+ filepath: full file path to a XLS or XLSX file to add to the\n+ importer.\n+ sheet_name: str, int, list, or None, default 0. Strings are used\n+ for sheet names. Integers are used in zero-indexed sheet\n+ positions. Lists of strings/integers are used to request\n+ multiple sheets. Specify None to get all sheets.\n+\n+ Raises:\n+ TypeError: if the entry is not an Excel sheet.\n+ \"\"\"\n+ self._ready()\n+ if not os.path.isfile(filepath):\n+ raise TypeError('File path is not a real file.')\n+\n+ file_ending = filepath.lower().split('.')[-1]\n+ if file_ending not in ['xls', 'xlsx']:\n+ raise TypeError('File name needs to end with xls or xlsx')\n+\n+ data_frame = pandas.read_excel(filepath, sheet_name=sheet_name)\n+ if data_frame.empty:\n+ raise TypeError('Not able to read any rows from sheet.')\n+\n+ self.add_data_frame(data_frame)\n+\ndef add_file(self, filepath, delimiter=','):\n\"\"\"Add a CSV, JSONL or a PLASO file to the buffer.\n" }, { "change_type": "MODIFY", "old_path": "docs/UploadDataViaAPI.md", "new_path": "docs/UploadDataViaAPI.md", "diff": "@@ -32,6 +32,7 @@ The importer will take as an input either:\n+ CSV or JSONL.\n+ JSON (one JSON per entry)\n+ Python dict\n+ + Microsoft Excel spreadsheet (XLS or XLSX file).\nThe best way to use the streamer is to by using the the `with` statement in\nPython, which returns back an object. Before you can use the streamer you'll\n@@ -175,3 +176,26 @@ Let's look at an example:\n```\n#TODO: Add an example here.\n```\n+\n+\n+## Excel Sheet\n+\n+```\n+from timesketch_api_client import client\n+from timesketch_api_client import importer\n+\n+...\n+def action():\n+\n+ ts = client.TimesketchApi(SERVER_LOCATION, USERNAME, PASSWORD)\n+ my_sketch = ts.get_sketch(SKETCH_ID)\n+\n+ with importer.ImportStreamer() as streamer:\n+ streamer.set_sketch(my_sketch)\n+ streamer.set_timestamp_description('Web Log')\n+ streamer.set_timeline_name('excel_import')\n+ streamer.set_message_format_string(\n+ '{What:s} resulted in {Results:s}, pointed from {URL:s}')\n+\n+ streamer.add_excel('~/Downloads/SomeRandomDocument.xlsx')\n+```\n" } ]
Python
Apache License 2.0
google/timesketch
Adding an excel read method.
263,096
27.10.2019 10:50:15
-3,600
e2478976901682e56f9abb68113be42f67d4300b
remove u' and fix typo
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -813,14 +813,14 @@ class Sketch(BaseResource):\na json data of the query.\n\"\"\"\nform_data = {\n- u'annotation': comment_text,\n- u'annotation_type': 'comment',\n- u'events': {\n+ 'annotation': comment_text,\n+ 'annotation_type': 'comment',\n+ 'events': {\n'_id': event_id,\n'_index': index,\n'_type': 'generic_event'}\n}\n- resource_url = u'{0:s}/sketches/{1:d}/event/annotate/'.format(\n+ resource_url = '{0:s}/sketches/{1:d}/event/annotate/'.format(\nself.api.api_root, self.id)\nresponse = self.api.session.post(resource_url, json=form_data)\nreturn response.json()\n@@ -1269,8 +1269,8 @@ class Timeline(BaseResource):\ntimeline_id: The primary key ID of the timeline.\nsketch_id: ID of a sketch.\napi: Instance of a TimesketchApi object.\n- name: Name of the timelne (optional)\n- searchindex: The Elasticsearch index name (optional)i\n+ name: Name of the timeline (optional)\n+ searchindex: The Elasticsearch index name (optional)\n\"\"\"\nself.id = timeline_id\nself._name = name\n" } ]
Python
Apache License 2.0
google/timesketch
remove u' and fix typo
263,133
28.10.2019 13:53:42
0
8a2864f2f6d8478bcee1752ea8ace3bf69db841d
Adding tests for the importer.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "-# Copyright 2017 Google Inc. All rights reserved.\n+# Copyright 2019 Google Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\nfrom __future__ import unicode_literals\nimport json\n+import math\n+import logging\nimport os\nimport tempfile\nimport uuid\n@@ -81,8 +83,11 @@ class ImportStreamer(object):\ndata_frame[column], utc=True)\n# We want the first successful timestamp value.\nbreak\n- except ValueError:\n- pass\n+ except ValueError as e:\n+ logging.info(\n+ 'Unable to convert timestamp in column: %s, error %s',\n+ column, e)\n+\nif 'timestamp' in data_frame:\ndata_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n'%Y-%m-%dT%H:%M:%S%z')\n@@ -179,9 +184,9 @@ class ImportStreamer(object):\nself._upload_data(csv_file.name, end_stream=True)\nreturn\n- chunks = int(size / self._threshold)\n+ chunks = int(math.ceil(float(size) / self._threshold))\nfor index in range(0, chunks):\n- chunk_start = index * chunks\n+ chunk_start = index * self._threshold\ndata_chunk = data_frame_use[\nchunk_start:chunk_start + self._threshold]\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/importer_test.py", "diff": "+# Copyright 2019 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Tests for the Timesketch importer.\"\"\"\n+from __future__ import unicode_literals\n+\n+import json\n+import unittest\n+import mock\n+\n+import pandas\n+\n+from . import importer\n+\n+\n+class MockSketch(object):\n+ \"\"\"Mock sketch object.\"\"\"\n+\n+ def __init__(self):\n+ self.api = mock.Mock()\n+ self.api.api_root = 'foo_root'\n+ self.id = 1\n+\n+\n+class MockStreamer(importer.ImportStreamer):\n+ \"\"\"Mock the import streamer.\"\"\"\n+\n+ def __init__(self, entry_threshold=None):\n+ super(MockStreamer, self).__init__(entry_threshold)\n+ self.files = []\n+ self.lines = []\n+ self.columns = []\n+\n+ def _upload_data(self, file_name, end_stream):\n+ self.files.append(file_name)\n+ with open(file_name, 'r') as fh:\n+ first_line = next(fh)\n+ self.columns = [x.strip() for x in first_line.split(',')]\n+ for line in fh:\n+ line = line.strip()\n+ self.lines.append(line)\n+\n+ def close(self):\n+ pass\n+\n+\n+class TimesketchImporterTest(unittest.TestCase):\n+ \"\"\"Test Timesketch importer.\"\"\"\n+\n+ def setUp(self):\n+ \"\"\"Set up the test data frame.\"\"\"\n+ self.lines = []\n+\n+ dict_one = {\n+ 'timestamp': '2019-02-23T12:51:52',\n+ 'stuff': 'from bar to foobar',\n+ 'correct': False,\n+ 'random_number': 13245,\n+ 'vital_stats': 'gangverk'\n+ }\n+ self.lines.append(dict_one)\n+\n+ dict_two = {\n+ 'timestamp': '2019-06-17T20:11:23',\n+ 'stuff': 'fra sjalfstaedi til sjalfstaedis',\n+ 'correct': True,\n+ 'random_number': 52,\n+ 'vital_stats': 'stolt'\n+ }\n+ self.lines.append(dict_two)\n+\n+ dict_three = {\n+ 'timestamp': '2019-01-03T02:39:42',\n+ 'stuff': 'stordagur',\n+ 'correct': True,\n+ 'random_number': 59913,\n+ 'vital_stats': 'elli'\n+ }\n+ self.lines.append(dict_three)\n+\n+ dict_four = {\n+ 'timestamp': '2019-12-23T23:00:03',\n+ 'stuff': 'sidasti sens ad kaupa gjof',\n+ 'correct': True,\n+ 'random_number': 5231134324,\n+ 'vital_stats': 'stress'\n+ }\n+ self.lines.append(dict_four)\n+\n+ dict_five = {\n+ 'timestamp': '2019-10-31T17:12:44',\n+ 'stuff': 'hraeda hraedur',\n+ 'correct': True,\n+ 'random_number': 420,\n+ 'vital_stats': 'grasker'\n+ }\n+ self.lines.append(dict_five)\n+\n+ self.frame = pandas.DataFrame(self.lines)\n+\n+ def test_adding_data_frames(self):\n+ \"\"\"Test adding a data frame to the importer.\"\"\"\n+\n+ with MockStreamer() as streamer:\n+ streamer.set_sketch(MockSketch())\n+ streamer.set_timestamp_description('Log Entries')\n+ streamer.set_timeline_name('Test Entries')\n+ streamer.set_message_format_string(\n+ '{stuff:s} -> {correct!s} [{random_number:d}]')\n+\n+ streamer.add_data_frame(self.frame)\n+ self._run_all_tests(streamer.columns, streamer.lines)\n+ self.assertEqual(len(streamer.files), 1)\n+\n+ # Test by splitting up the dataset into chunks.\n+ lines = None\n+ files = None\n+ columns = None\n+ with MockStreamer(2) as streamer:\n+ streamer.set_sketch(MockSketch())\n+ streamer.set_timestamp_description('Log Entries')\n+ streamer.set_timeline_name('Test Entries')\n+ streamer.set_message_format_string(\n+ '{stuff:s} -> {correct!s} [{random_number:d}]')\n+\n+ streamer.add_data_frame(self.frame)\n+ lines = streamer.lines\n+ files = streamer.files\n+ columns = streamer.columns\n+ self._run_all_tests(columns, lines)\n+ self.assertEqual(len(files), 3)\n+\n+ def test_adding_dict(self):\n+ \"\"\"Test adding a dict to the importer.\"\"\"\n+ with MockStreamer() as streamer:\n+ streamer.set_sketch(MockSketch())\n+ streamer.set_timestamp_description('Log Entries')\n+ streamer.set_timeline_name('Test Entries')\n+ streamer.set_message_format_string(\n+ '{stuff:s} -> {correct!s} [{random_number:d}]')\n+\n+ for entry in self.lines:\n+ streamer.add_dict(entry)\n+\n+ streamer.flush()\n+ self._run_all_tests(streamer.columns, streamer.lines)\n+\n+ def test_adding_json(self):\n+ \"\"\"Test adding a JSON to the importer.\"\"\"\n+ with MockStreamer() as streamer:\n+ streamer.set_sketch(MockSketch())\n+ streamer.set_timestamp_description('Log Entries')\n+ streamer.set_timeline_name('Test Entries')\n+ streamer.set_message_format_string(\n+ '{stuff:s} -> {correct!s} [{random_number:d}]')\n+\n+ for entry in self.lines:\n+ json_string = json.dumps(entry)\n+ streamer.add_json(json_string)\n+\n+ streamer.flush()\n+ self._run_all_tests(streamer.columns, streamer.lines)\n+\n+ def _run_all_tests(self, columns, lines):\n+ \"\"\"Run all tests on the result set of a streamer.\"\"\"\n+ # The first line is the column line.\n+ self.assertEqual(len(lines), 5)\n+\n+ column_set = set(columns)\n+ correct_set = set([\n+ 'message', 'timestamp_desc', 'datetime', 'timestamp',\n+ 'vital_stats', 'random_number', 'correct', 'stuff'])\n+\n+ self.assertSetEqual(column_set, correct_set)\n+\n+ message_index = columns.index('message')\n+ messages = []\n+ for line in lines:\n+ message = line.split(',')[message_index]\n+ messages.append(message)\n+\n+ message_correct = set([\n+ 'fra sjalfstaedi til sjalfstaedis -> True [52]',\n+ 'from bar to foobar -> False [13245]',\n+ 'sidasti sens ad kaupa gjof -> True [5231134324]',\n+ 'stordagur -> True [59913]',\n+ 'hraeda hraedur -> True [420]',\n+ ])\n+ self.assertSetEqual(set(messages), message_correct)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -470,7 +470,7 @@ def run_csv_jsonl(source_file_path, timeline_name, index_name, source_type):\n# Reason for the broad exception catch is that we want to capture\n# all possible errors and exit the task.\ntry:\n- items = es.create_index(index_name=index_name, doc_type=event_type)\n+ es.create_index(index_name=index_name, doc_type=event_type)\nfor event in read_and_validate(source_file_path):\nes.import_event(index_name, event_type, event)\n# Import the remaining events\n" } ]
Python
Apache License 2.0
google/timesketch
Adding tests for the importer.
263,133
28.10.2019 15:36:22
0
fbb629b5c5faa2eb8d9f786de644e251887c5843
Adding the ability to list available analyzers in the client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -39,5 +39,6 @@ setup(\ninstall_requires=frozenset([\n'pandas',\n'requests',\n+ 'xlrd',\n'beautifulsoup4']),\n)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -699,6 +699,19 @@ class Sketch(BaseResource):\nreturn response_json\n+ def list_available_analyzers(self):\n+ \"\"\"Returns a list of available analyzers.\"\"\"\n+ resource_url = '{0:s}/sketches/{1:d}/analyzer/'.format(\n+ self.api.api_root, self.id)\n+\n+ response = self.api.session.get(resource_url)\n+\n+ if response.status_code == 200:\n+ return response.json()\n+\n+ return '[{0:d}] {1:s} {2:s}'.format(\n+ response.status_code, response.reason, response.text)\n+\ndef run_analyzer(\nself, analyzer_name, analyzer_kwargs=None, timeline_id=None,\ntimeline_name=None):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1848,10 +1848,16 @@ class AnalyzerRunResource(ResourceMixin, Resource):\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\n+ try:\nsketch_analyzer_group = tasks.build_sketch_analysis_pipeline(\nsketch_id=sketch_id, searchindex_id=search_index.id,\nuser_id=current_user.id, analyzer_names=[analyzer_name],\nanalyzer_kwargs=analyzer_kwargs)\n+ except KeyError as e:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to build analyzer pipeline, analyzer does not exist. '\n+ 'Error message: {0!s}'.format(e))\nif sketch_analyzer_group:\npipeline = (tasks.run_sketch_init.s(\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to list available analyzers in the client.
263,133
28.10.2019 15:50:28
0
e6f2eb543046124a9edd29f4b53678b9a36cc43f
Minor bug in the list aggregation.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -396,7 +396,7 @@ class Sketch(BaseResource):\n\"\"\"\ndata = self.lazyload_data()\naggregations = []\n- for aggregation in data['aggregations']:\n+ for aggregation in data.get('aggregations', []):\naggregation_obj = Aggregation(\nsketch=self, api=self.api)\naggregation_obj.from_store(aggregation_id=aggregation['id'])\n@@ -414,7 +414,7 @@ class Sketch(BaseResource):\notherwise None object.\n\"\"\"\nsketch = self.lazyload_data()\n- for aggregation in sketch['aggregations']:\n+ for aggregation in sketch.get('aggregations', []):\nif aggregation['id'] != aggregation_id:\ncontinue\naggregation_obj = Aggregation(sketch=self, api=self.api)\n@@ -851,6 +851,9 @@ class Sketch(BaseResource):\naggregator_parameters: parameters of the aggregator.\nchart_type: string representing the chart type.\n+ Raises:\n+ RuntimeError: if the client is unable to store the aggregation.\n+\nReturns:\nA stored aggregation object or None if not stored.\n\"\"\"\n@@ -867,6 +870,12 @@ class Sketch(BaseResource):\n}\nresponse = self.api.session.post(resource_url, json=form_data)\n+ if response.status_code not in HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Error storing the aggregation, Error message: '\n+ '[{0:d}] {1:s} {2:s}'.format(\n+ response.status_code, response.reason, response.text))\n+\nresponse_dict = response.json()\nobjects = response_dict.get('objects', [])\n" } ]
Python
Apache License 2.0
google/timesketch
Minor bug in the list aggregation.
263,133
28.10.2019 16:35:09
0
42cc9418b4962f002c0f75f9f6d089f202dde6d7
Upgrading client version.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20191018',\n+ version='20191028',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Upgrading client version.
263,133
28.10.2019 20:03:06
0
793b91864ea4e7838655cbf7e2a6054e45dc6c11
Expanding excel imports.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -216,16 +216,34 @@ class ImportStreamer(object):\nself._data_lines.append(entry)\nself._count += 1\n- def add_excel_file(self, filepath, sheet_name=0):\n+ def add_excel_file(self, filepath, **kwargs):\n\"\"\"Add a Microsoft Excel sheet to importer.\nArgs:\nfilepath: full file path to a XLS or XLSX file to add to the\nimporter.\n- sheet_name: str, int, list, or None, default 0. Strings are used\n- for sheet names. Integers are used in zero-indexed sheet\n- positions. Lists of strings/integers are used to request\n- multiple sheets. Specify None to get all sheets.\n+ kwargs:\n+ Other parameters can be passed in that match the\n+ pandas.read_excel parameters. Including:\n+\n+ sheet_name: str, int, list, or None, default 0. Strings are\n+ used for sheet names. Integers are used in zero-indexed\n+ sheet positions. Lists of strings/integers are used to\n+ request multiple sheets. Specify None to get all sheets.\n+ header : int, list of int, default 0\n+ Row (0-indexed) to use for the column labels of the\n+ parsed DataFrame. If a list of integers is passed those\n+ row positions wil be combined into a ``MultiIndex``. Use\n+ None if there is no header.\n+ names : array-like, default None\n+ List of column names to use. If file contains no header\n+ row then you should explicitly pass header=None.\n+ index_col : int, list of int, default None\n+ Column (0-indexed) to use as the row labels of the\n+ DataFrame. Pass None if there is no such column. If a list\n+ is passed, those columns will be combined into a\n+ ``MultiIndex``. If a subset of data is selected with\n+ ``usecols``, index_col is based on the subset.\nRaises:\nTypeError: if the entry is not an Excel sheet.\n@@ -238,7 +256,7 @@ class ImportStreamer(object):\nif file_ending not in ['xls', 'xlsx']:\nraise TypeError('File name needs to end with xls or xlsx')\n- data_frame = pandas.read_excel(filepath, sheet_name=sheet_name)\n+ data_frame = pandas.read_excel(filepath, **kwargs)\nif data_frame.empty:\nraise TypeError('Not able to read any rows from sheet.')\n" } ]
Python
Apache License 2.0
google/timesketch
Expanding excel imports.
263,133
29.10.2019 14:42:20
0
e3b93935f736672ed0d1b9a896b7ab00beff9f68
Responding to comments, as well as simplifying API calls.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -533,6 +533,9 @@ class Sketch(BaseResource):\nRaises:\nValueError: if the dataframe cannot be uploaded to Timesketch.\n\"\"\"\n+ # TODO: Explore the option of supporting YAML files for loading\n+ # configs for formatting strings. (this would be implemented\n+ # in the streamer itself, but accepted here as a parameter).\nif not format_message_string:\nstring_items = []\nfor column in data_frame.columns:\n@@ -543,7 +546,7 @@ class Sketch(BaseResource):\nstring_items.append('{0:s} = {{0!s}}'.format(column))\nformat_message_string = ' '.join(string_items)\n- response = None\n+ streamer_response = None\nwith importer.ImportStreamer() as streamer:\nstreamer.set_sketch(self)\nstreamer.set_timeline_name(timeline_name)\n@@ -551,17 +554,17 @@ class Sketch(BaseResource):\nstreamer.set_message_format_string(format_message_string)\nstreamer.add_data_frame(data_frame)\n- response = streamer.response\n+ streamer_response = streamer.response\n- if not response:\n+ if not streamer_response:\nreturn 'No return value.'\nreturn_lines = []\n- for timesketch_object in response.get('objects', []):\n+ for sketch_object in streamer_response.get('objects', []):\nreturn_lines.append('Timeline: {0:s}\\nStatus: {1:s}'.format(\n- timesketch_object.get('description'),\n+ sketch_object.get('description'),\n','.join([x.get(\n- 'status') for x in timesketch_object.get('status')])))\n+ 'status') for x in sketch_object.get('status')])))\nreturn '\\n'.join(return_lines)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -341,7 +341,11 @@ class ImportStreamer(object):\nexcept ValueError:\nreturn\n- pipe_resource = '{0:s}/sketches/{1:d}/analyzer/auto_run/'.format(\n+ if self._data_lines:\n+ self.flush(end_stream=True)\n+\n+ # Trigger auto analyzer pipeline to kick in.\n+ pipe_resource = '{0:s}/sketches/{1:d}/analyzer/'.format(\nself._sketch.api.api_root, self._sketch.id)\ndata = {\n'index_name': self._index\n@@ -418,5 +422,4 @@ class ImportStreamer(object):\n# pylint: disable=unused-argument\ndef __exit__(self, exception_type, exception_value, traceback):\n\"\"\"Make it possible to use \"with\" statement.\"\"\"\n- self.flush(end_stream=True)\nself.close()\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -71,7 +71,6 @@ from timesketch.lib.emojis import get_emojis_as_dict\nfrom timesketch.lib.forms import AddTimelineSimpleForm\nfrom timesketch.lib.forms import AggregationExploreForm\nfrom timesketch.lib.forms import AggregationLegacyForm\n-from timesketch.lib.forms import AnalyzerPipelineForm\nfrom timesketch.lib.forms import CreateTimelineForm\nfrom timesketch.lib.forms import SaveAggregationForm\nfrom timesketch.lib.forms import SaveViewForm\n@@ -83,7 +82,6 @@ from timesketch.lib.forms import UploadFileForm\nfrom timesketch.lib.forms import StoryForm\nfrom timesketch.lib.forms import GraphExploreForm\nfrom timesketch.lib.forms import SearchIndexForm\n-from timesketch.lib.forms import RunAnalyzerForm\nfrom timesketch.lib.forms import TimelineForm\nfrom timesketch.lib.utils import get_validated_indices\nfrom timesketch.lib.experimental.utils import GRAPH_VIEWS\n@@ -1369,50 +1367,6 @@ class EventAnnotationResource(ResourceMixin, Resource):\nannotations, status_code=HTTP_STATUS_CODE_CREATED)\n-class AnalyzerPipelineResource(ResourceMixin, Resource):\n- \"\"\"Resource to start analyzer pipeline.\"\"\"\n-\n- @login_required\n- def post(self, sketch_id):\n- \"\"\"Handles POST request to the resource.\n-\n- Returns:\n- A string with information on pipeline.\n- \"\"\"\n- form = AnalyzerPipelineForm()\n- if not form.validate_on_submit():\n- abort(\n- HTTP_STATUS_CODE_BAD_REQUEST,\n- 'Unable to validate the input form.')\n-\n- sketch = Sketch.query.get_with_acl(sketch_id)\n- if not sketch.has_permission(current_user, 'write'):\n- abort(\n- HTTP_STATUS_CODE_FORBIDDEN,\n- 'User does not have write access to sketch')\n-\n- index_name = form.index_name.data\n- searchindex = SearchIndex.query.filter_by(\n- user=current_user,\n- index_name=index_name).first()\n- if not searchindex:\n- abort(\n- HTTP_STATUS_CODE_BAD_REQUEST,\n- 'There is no searchindex for index name: {0:s}'.format(\n- index_name))\n-\n- # Start Celery pipeline for indexing and analysis.\n- # Import here to avoid circular imports.\n- from timesketch.lib import tasks\n- pipeline = tasks.build_sketch_analysis_pipeline(\n- sketch_id, searchindex.id, user_id=None)\n-\n- if pipeline:\n- pipeline = (tasks.run_sketch_init.s(\n- [index_name]) | pipeline)\n- pipeline.apply_async()\n-\n-\nclass UploadFileResource(ResourceMixin, Resource):\n\"\"\"Resource that processes uploaded files.\"\"\"\n@@ -1822,18 +1776,19 @@ class AnalyzerRunResource(ResourceMixin, Resource):\nHTTP_STATUS_CODE_FORBIDDEN,\n'User does not have write permission on the sketch.')\n- form = RunAnalyzerForm.build(request)\n- if not form.validate_on_submit():\n+ form = request.json\n+\n+ timeline_id = form.get('timeline_id')\n+ if not timeline_id:\nreturn abort(\n- HTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate input data.')\n+ HTTP_STATUS_CODE_BAD_REQUEST, 'Need to provide a timeline ID.')\nsearch_index = None\n- timeline_id = form.timeline_id.data\nfor timeline in sketch.timelines:\nindex = SearchIndex.query.get_with_acl(\ntimeline.searchindex_id)\n- if index.index_name.lower() == timeline_id:\n+ if index.index_name.lower() == timeline_id.lower():\nsearch_index = index\nbreak\n@@ -1843,15 +1798,24 @@ class AnalyzerRunResource(ResourceMixin, Resource):\n'No timeline was found, make sure you\\'ve got the correct '\n'timeline ID or timeline name.'))\n- analyzer_name = form.analyzer_name.data\n- analyzer_kwargs = form.analyzer_kwargs.data\n+ analyzer_name = form.get('analyzer_name')\n+ if analyzer_name:\n+ if not isinstance(analyzer_name, (tuple, list)):\n+ analyzer_name = [analyzer_name]\n+\n+ analyzer_kwargs = form.get('analyzer_kwargs')\n+ if analyzer_kwargs:\n+ if not isinstance(analyzer_kwargs, dict):\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'KWargs needs to be a dictionary of parameters.')\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\ntry:\nsketch_analyzer_group = tasks.build_sketch_analysis_pipeline(\nsketch_id=sketch_id, searchindex_id=search_index.id,\n- user_id=current_user.id, analyzer_names=[analyzer_name],\n+ user_id=current_user.id, analyzer_names=analyzer_name,\nanalyzer_kwargs=analyzer_kwargs)\nexcept KeyError as e:\nreturn abort(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/routes.py", "new_path": "timesketch/api/v1/routes.py", "diff": "@@ -20,7 +20,6 @@ from .resources import AggregationLegacyResource\nfrom .resources import AggregationExploreResource\nfrom .resources import AggregationResource\nfrom .resources import AnalyzerRunResource\n-from .resources import AnalyzerPipelineResource\nfrom .resources import ExploreResource\nfrom .resources import EventResource\nfrom .resources import EventAnnotationResource\n@@ -54,7 +53,6 @@ API_ROUTES = [\n(SketchListResource, '/sketches/'),\n(SketchResource, '/sketches/<int:sketch_id>/'),\n(AnalyzerRunResource, '/sketches/<int:sketch_id>/analyzer/'),\n- (AnalyzerPipelineResource, '/sketches/<int:sketch_id>/analyzer/auto_run/'),\n(AggregationListResource, '/sketches/<int:sketch_id>/aggregation/'),\n(AggregationLegacyResource, '/sketches/<int:sketch_id>/aggregation/legacy/'),\n(AggregationExploreResource, '/sketches/<int:sketch_id>/aggregation/explore/'),\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/forms.py", "new_path": "timesketch/lib/forms.py", "diff": "@@ -182,14 +182,6 @@ class GraphExploreForm(BaseForm):\noutput_format = StringField('Output format')\n-class RunAnalyzerForm(BaseForm):\n- \"\"\"Form used to run an analyzer on a timeline.\"\"\"\n- timeline_id = StringField('Timeline Index ID', validators=[Optional()])\n- analyzer_name = StringField('Analyzer name')\n- analyzer_kwargs = StringField(\n- 'Parameters for the analyzer', validators=[Optional()])\n-\n-\nclass SaveAggregationForm(BaseForm):\n\"\"\"Form used to save an aggregation.\"\"\"\nname = StringField('Name')\n@@ -245,11 +237,6 @@ class EventAnnotationForm(BaseForm):\nevents = StringField('Events', validators=[DataRequired()])\n-class AnalyzerPipelineForm(BaseForm):\n- \"\"\"Form to start analyzer pipeline.\"\"\"\n- index_name = StringField('Index Name', validators=[Optional()])\n-\n-\nclass UploadFileForm(BaseForm):\n\"\"\"Form to handle file uploads.\"\"\"\nfile = FileField(\n" } ]
Python
Apache License 2.0
google/timesketch
Responding to comments, as well as simplifying API calls.
263,133
29.10.2019 15:01:57
0
ae371fa1619dd4a4e591a828de3470cd319f0712
Making minor changes to the analyzer form resource.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -765,7 +765,7 @@ class Sketch(BaseResource):\ntimeline_id = timelines[0]\ndata = {\n- 'timeline_id': timeline_id,\n+ 'index_name': timeline_id,\n'analyzer_name': analyzer_name,\n'analyzer_kwargs': analyzer_kwargs,\n}\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -350,7 +350,7 @@ class ImportStreamer(object):\ndata = {\n'index_name': self._index\n}\n- _ = self._sketch.api.session.post(pipe_resource, data=data)\n+ _ = self._sketch.api.session.post(pipe_resource, json=data)\ndef flush(self, end_stream=True):\n\"\"\"Flushes the buffer and uploads to timesketch.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1777,18 +1777,26 @@ class AnalyzerRunResource(ResourceMixin, Resource):\n'User does not have write permission on the sketch.')\nform = request.json\n+ if not form:\n+ form = request.data\n- timeline_id = form.get('timeline_id')\n- if not timeline_id:\n+ if not form:\nreturn abort(\n- HTTP_STATUS_CODE_BAD_REQUEST, 'Need to provide a timeline ID.')\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'Unable to run an analyzer without any data submitted.')\n+\n+ index_name = form.get('index_name')\n+ if not index_name:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Need to provide a timeline index ID.')\nsearch_index = None\nfor timeline in sketch.timelines:\nindex = SearchIndex.query.get_with_acl(\ntimeline.searchindex_id)\n- if index.index_name.lower() == timeline_id.lower():\n+ if index.index_name.lower() == index_name.lower():\nsearch_index = index\nbreak\n@@ -1808,7 +1816,7 @@ class AnalyzerRunResource(ResourceMixin, Resource):\nif not isinstance(analyzer_kwargs, dict):\nreturn abort(\nHTTP_STATUS_CODE_BAD_REQUEST,\n- 'KWargs needs to be a dictionary of parameters.')\n+ 'Kwargs needs to be a dictionary of parameters.')\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\n" } ]
Python
Apache License 2.0
google/timesketch
Making minor changes to the analyzer form resource.
263,133
29.10.2019 15:24:33
0
59251d345d949c46da4cd3402c1b7382ec5e8175
Changing analyzer_name to analyzer_names
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -766,7 +766,7 @@ class Sketch(BaseResource):\ndata = {\n'index_name': timeline_id,\n- 'analyzer_name': analyzer_name,\n+ 'analyzer_names': [analyzer_name],\n'analyzer_kwargs': analyzer_kwargs,\n}\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1816,10 +1816,12 @@ class AnalyzerRunResource(ResourceMixin, Resource):\n'No timeline was found, make sure you\\'ve got the correct '\n'timeline ID or timeline name.'))\n- analyzer_name = form.get('analyzer_name')\n- if analyzer_name:\n- if not isinstance(analyzer_name, (tuple, list)):\n- analyzer_name = [analyzer_name]\n+ analyzer_names = form.get('analyzer_names')\n+ if analyzer_names:\n+ if not isinstance(analyzer_names, (tuple, list)):\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Analyzer names needs to be a list of analyzers.')\nanalyzer_kwargs = form.get('analyzer_kwargs')\nif analyzer_kwargs:\n@@ -1833,7 +1835,7 @@ class AnalyzerRunResource(ResourceMixin, Resource):\ntry:\nsketch_analyzer_group = tasks.build_sketch_analysis_pipeline(\nsketch_id=sketch_id, searchindex_id=search_index.id,\n- user_id=current_user.id, analyzer_names=analyzer_name,\n+ user_id=current_user.id, analyzer_names=analyzer_names,\nanalyzer_kwargs=analyzer_kwargs)\nexcept KeyError as e:\nreturn abort(\n" } ]
Python
Apache License 2.0
google/timesketch
Changing analyzer_name to analyzer_names
263,133
01.11.2019 10:13:10
0
5d2363d19f09f578122218f857a40ef90b32a687
Fixing few things.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain.py", "new_path": "timesketch/lib/analyzers/chain.py", "diff": "@@ -86,11 +86,11 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\nchain_id_list = event.source.get('chain_id_list', [])\nchain_id_list.append(chain_id)\n- chain_plugins = event.source.get('chain_plugins', [])\n- chain_plugins.append(chain_plugin.NAME)\n+ chain_plugins_list = event.source.get('chain_plugins', [])\n+ chain_plugins_list.append(chain_plugin.NAME)\nattributes = {\n'chain_id_list': chain_id_list,\n- 'chain_plugins': chain_plugins}\n+ 'chain_plugins': chain_plugins_list}\nevent.add_attributes(attributes)\nevent.add_emojis([link_emoji])\nevent.commit()\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_test.py", "new_path": "timesketch/lib/analyzers/chain_test.py", "diff": "@@ -67,10 +67,10 @@ class FakeChainPlugin(interface.BaseChainPlugin):\nEVENT_FIELDS = ['kedjur']\nALL_EVENTS = []\n- def ProcessChain(self, base_event):\n+ def process_chain(self, base_event):\nreturn True\n- def GetChainedEvents(self, base_event):\n+ def get_chained_events(self, base_event):\n\"\"\"Implementation of the chained events.\"\"\"\nurl = base_event.source.get('url', '')\ntenging = base_event.source.get('tenging', '')\n@@ -109,10 +109,10 @@ class TestChainAnalyzer(testlib.BaseTest):\ndef test_get_chains(self):\n\"\"\"Test the chain.\"\"\"\n- for plugin in manager.ChainPluginsManager.GetPlugins(None):\n+ for plugin in manager.ChainPluginsManager.get_plugins(None):\nmanager.ChainPluginsManager.DeregisterPlugin(plugin)\n- manager.ChainPluginsManager.RegisterPlugin(FakeChainPlugin)\n+ manager.ChainPluginsManager.register_plugin(FakeChainPlugin)\nanalyzer = FakeAnalyzer('test_index', sketch_id=1)\nanalyzer.datastore.client = mock.Mock()\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing few things.
263,133
01.11.2019 10:40:21
0
f3e3c7b697ec2d4f88f6858a62bd65074a4b2f9d
Fixing failed test.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_test.py", "new_path": "timesketch/lib/analyzers/chain_test.py", "diff": "@@ -132,7 +132,8 @@ class TestChainAnalyzer(testlib.BaseTest):\nlink_emoji = emojis.get_emoji('LINK')\nfor event in plugin.ALL_EVENTS:\nattributes = event.attributes\n- self.assertEqual(attributes.get('chain_plugin', ''), 'fake_chain')\n+ self.assertEqual(\n+ attributes.get('chain_plugins', []), ['fake_chain'])\nevent_emojis = event.emojis\nself.assertEqual(len(event_emojis), 1)\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing failed test.
263,093
05.11.2019 11:02:34
-3,600
1be65f20922452447b775b4aae40d3b9333f63a5
Allow running analyzers for users with READ permission
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1855,10 +1855,10 @@ class AnalyzerRunResource(ResourceMixin, Resource):\nA string with the response from running the analyzer.\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n- if not sketch.has_permission(current_user, 'write'):\n+ if not sketch.has_permission(current_user, 'read'):\nreturn abort(\nHTTP_STATUS_CODE_FORBIDDEN,\n- 'User does not have write permission on the sketch.')\n+ 'User does not have read permission on the sketch.')\nform = request.json\nif not form:\n" } ]
Python
Apache License 2.0
google/timesketch
Allow running analyzers for users with READ permission
263,133
05.11.2019 13:36:23
0
bce99cb4bc6d1824842f70ea57f3f0cc4da0bae7
Fixing a py3/py2 issue with urlencode
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/google_auth.py", "new_path": "timesketch/lib/google_auth.py", "diff": "@@ -22,7 +22,11 @@ import time\nimport json\nimport hashlib\nimport os\n-import urllib\n+\n+# six.moves is a dynamically-created namespace that doesn't actually\n+# exist and therefore pylint can't statically analyze it.\n+# pylint: disable-msg=import-error\n+from six.moves.urllib import parse as urlparse\nimport jwt\nimport requests\n@@ -136,7 +140,7 @@ def get_oauth2_authorize_url(hosted_domain=None):\nif hosted_domain:\nparams['hd'] = hosted_domain\n- urlencoded_params = urllib.urlencode(params)\n+ urlencoded_params = urlparse.urlencode(params)\ngoogle_authorization_url = '{}?{}'.format(AUTH_URI, urlencoded_params)\nreturn google_authorization_url\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing a py3/py2 issue with urlencode
263,133
14.11.2019 08:26:51
0
ebe9c2b87bf3ddb287bb5ca4aa16f37e3109b899
Making minor changes to OAUTH handling for API client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20191110',\n+ version='20191114',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -41,7 +41,7 @@ def _error_message(response, message=None, error=RuntimeError):\ntext = ''\nif soup.p:\ntext = soup.p.string\n- raise error('{0:s}, with error [{1:d}] {2:s} {3:s}'.format(\n+ raise error('{0:s}, with error [{1:d}] {2!s} {3:s}'.format(\nmessage, response.status_code, response.reason, text))\n@@ -93,8 +93,6 @@ class TimesketchApi(object):\n\"\"\"\nself._host_uri = host_uri\nself.api_root = '{0:s}/api/v1'.format(host_uri)\n- self._redirect_uri = '{0:s}/login/google_openid_connect/'.format(\n- host_uri)\nself._credentials = None\nself._flow = None\ntry:\n@@ -146,12 +144,14 @@ class TimesketchApi(object):\n'referer': self._host_uri\n})\n- def _create_oauth_session(self, client_id, client_secret):\n+ def _create_oauth_session(self, client_id, client_secret, skip_open=False):\n\"\"\"Return an OAuth session.\nArgs:\nclient_id: The client ID if OAUTH auth is used.\nclient_secret: The OAUTH client secret if OAUTH is used.\n+ skip_open: If set to True then an auth URL will be printed, instead\n+ of presenting an option to open a browser window.\nReturn:\nsession: Instance of requests.Session.\n@@ -175,11 +175,16 @@ class TimesketchApi(object):\nflow.redirect_uri = self.DEFAULT_OAUTH_OOB_URL\nauth_url, _ = flow.authorization_url(prompt='select_account')\n+ if skip_open:\n+ print('Visit the following URL to authenticate: {0:s}'.format(\n+ auth_url))\n+ else:\nopen_browser = input('Open the URL in a browser window? [y/N] ')\nif open_browser.lower() == 'y' or open_browser.lower() == 'yes':\nwebbrowser.open(auth_url)\nelse:\n- print('Need to manually URL to authenticate: {0:s}'.format(\n+ print(\n+ 'Need to manually visit URL to authenticate: {0:s}'.format(\nauth_url))\ncode = input('Enter the token code: ')\n@@ -192,7 +197,10 @@ class TimesketchApi(object):\n# Authenticate to the Timesketch backend.\nlogin_callback_url = '{0:s}{1:s}'.format(\nself._host_uri, self.DEFAULT_OAUTH_API_CALLBACK)\n- response = session.get(login_callback_url)\n+ data = {\n+ 'id_token': session.credentials.id_token,\n+ }\n+ response = session.post(login_callback_url, data=data)\nif response.status_code not in HTTP_STATUS_CODE_20X:\n_error_message(\n@@ -689,7 +697,7 @@ class Sketch(BaseResource):\nfor column in data_frame.columns:\nif 'time' in column:\ncontinue\n- elif 'timestamp_desc' in column:\n+ if 'timestamp_desc' in column:\ncontinue\nstring_items.append('{0:s} = {{0!s}}'.format(column))\nformat_message_string = ' '.join(string_items)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/views/auth.py", "new_path": "timesketch/views/auth.py", "diff": "@@ -53,7 +53,6 @@ from timesketch.models.user import User\n# Register flask blueprint\nauth_views = Blueprint('user_views', __name__)\n-PROFILE_URI = 'https://www.googleapis.com/oauth2/v3/userinfo'\nTOKEN_URI = 'https://www.googleapis.com/oauth2/v3/tokeninfo'\nSCOPES = [\n'https://www.googleapis.com/auth/userinfo.email',\n@@ -185,6 +184,12 @@ def validate_api_token():\nreturn abort(\nHTTP_STATUS_CODE_UNAUTHORIZED, 'Request not authenticated.')\n+ data = request.data\n+ id_token = data.get('id_token')\n+ if not id_token:\n+ return abort(\n+ HTTP_STATUS_CODE_UNAUTHORIZED, 'No ID token supplied.')\n+\nclient_id = current_app.config.get('GOOGLE_OIDC_API_CLIENT_ID')\nif not client_id:\nreturn abort(\n@@ -198,10 +203,16 @@ def validate_api_token():\n# is valid, to be able to validate the session.\ndata = {\n'access_token': token}\n- token_response = requests.post(TOKEN_URI, data=data)\n- if token_response.status_code != HTTP_STATUS_CODE_OK:\n+ bearer_token_response = requests.post(TOKEN_URI, data=data)\n+ if bearer_token_response.status_code != HTTP_STATUS_CODE_OK:\nreturn abort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate access token.')\n+ bearer_token_json = bearer_token_response.json()\n+\n+ data = {\n+ 'id_token': id_token\n+ }\n+ token_response = requests.post(TOKEN_URI, data=data)\ntoken_json = token_response.json()\nverified = token_json.get('email_verified', False)\n@@ -210,25 +221,15 @@ def validate_api_token():\nHTTP_STATUS_CODE_UNAUTHORIZED,\n'Session not authenticated or account not verified')\n- # Get additional information, see more details here:\n- # https://www.oauth.com/oauth2-servers/signing-in-with-google/\\\n- # verifying-the-user-info/\n- # Getting user information, since JWT session using access token\n- # lacks some of the fields available if credential token is\n- # used (which is not available for use here).\n- authorization_header = request.headers.get('Authorization')\n- if authorization_header:\n- header = {'Authorization': authorization_header}\n- else:\n- header = {}\n-\n- profile_response = requests.get(PROFILE_URI, headers=header)\n- if profile_response.status_code != HTTP_STATUS_CODE_OK:\n+ if bearer_token_json.get('azp', 'a') != token_json.get('azp', 'x'):\nreturn abort(\n- HTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate profile.')\n+ HTTP_STATUS_CODE_UNAUTHORIZED,\n+ 'Auth token and client tokens don\\'t match, azp differs.')\n- profile = profile_response.json()\n- token_json['hd'] = profile.get('hd', '')\n+ if bearer_token_json.get('email', 'a') != token_json.get('email', 'b'):\n+ return abort(\n+ HTTP_STATUS_CODE_UNAUTHORIZED,\n+ 'Auth token and client tokens don\\'t match, email differs.')\nexpected_issuer = current_app.config.get('GOOGLE_IAP_ISSUER')\ntry:\n@@ -254,7 +255,6 @@ def validate_api_token():\n'Client scopes differ from what they should be (email, openid, '\n'profile) = {} VS {}'.format(SCOPES, read_scopes))\n- user_whitelist = current_app.config.get('GOOGLE_OIDC_USER_WHITELIST')\nvalidated_email = token_json.get('email')\n# Check if the authenticating user is part of the allowed domains.\n@@ -267,6 +267,7 @@ def validate_api_token():\n'Domain {0:s} is not allowed to authenticate against this '\n'instance.'.format(domain))\n+ user_whitelist = current_app.config.get('GOOGLE_OIDC_USER_WHITELIST')\n# Check if the authenticating user is on the whitelist.\nif user_whitelist:\nif validated_email not in user_whitelist:\n" } ]
Python
Apache License 2.0
google/timesketch
Making minor changes to OAUTH handling for API client.
263,133
14.11.2019 13:02:16
0
3b00acd65779d87337b32ea503a79e69bdd5ed76
Making more changes.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -117,14 +117,18 @@ class TimesketchApi(object):\ndata = {'username': username, 'password': password}\nsession.post('{0:s}/login/'.format(self._host_uri), data=data)\n- def _set_csrf_token(self, session):\n+ def _set_csrf_token(self, session, url=None):\n\"\"\"Retrieve CSRF token from the server and append to HTTP headers.\nArgs:\nsession: Instance of requests.Session.\n+ url: Optional URL to fetch the token from, if not used the host\n+ URI will be visited.\n\"\"\"\n# Scrape the CSRF token from the response\n- response = session.get(self._host_uri)\n+ if not url:\n+ url = self._host_uri\n+ response = session.get(url)\nsoup = bs4.BeautifulSoup(response.text, features='html.parser')\ntag = soup.find(id='csrf_token')\n@@ -200,13 +204,14 @@ class TimesketchApi(object):\ndata = {\n'id_token': session.credentials.id_token,\n}\n- response = session.post(login_callback_url, data=data)\n+ # Do a callback to get the CSRF token before we authenticate.\n+ self._set_csrf_token(session, login_callback_url)\n+ response = session.post(login_callback_url, data=data)\nif response.status_code not in HTTP_STATUS_CODE_20X:\n_error_message(\nresponse, message='Unable to authenticate', error=RuntimeError)\n- self._set_csrf_token(session)\nreturn session\ndef _create_session(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/views/auth.py", "new_path": "timesketch/views/auth.py", "diff": "@@ -168,13 +168,32 @@ def logout():\nreturn redirect(url_for('user_views.login'))\n-@auth_views.route('/login/api_callback/', methods=['GET'])\n+@auth_views.route('/login/api_callback/', methods=['GET', 'POST'])\ndef validate_api_token():\n\"\"\"Handler for logging in using an authenticated session for the API.\nReturns:\nA simple page indicating the user is authenticated.\n\"\"\"\n+ print('IN THE API CALLBACK')\n+ if request.method == 'GET':\n+ print('WE GOT A GET, LET FETCH OURSELVES THE CSRF TOKEN')\n+ hosted_domain = current_app.config.get('GOOGLE_OIDC_HOSTED_DOMAIN')\n+ url = get_oauth2_authorize_url(hosted_domain)\n+ print(url)\n+ return (\n+ '<html lang=\"en\">\\n'\n+ '<head>\\n'\n+ '<title>Timesketch</title>\\n'\n+ '<meta name=\"csrf-token\" content=\"{0:s}\">\\n'\n+ '<link rel=\"shortcut icon\" href=\"/static/img/favicon.ico\">\\n'\n+ '<link rel=\"stylesheet\" href=\"/static/dist/bundle.css\">\\n'\n+ '<script type=\"text/javascript\" language=\"javascript\" src=\"/static/dist/bundle.js\"></script>\\n'\n+ '</head>\\n'\n+ '<body><h1>Successful GET request made</h1></body>\\n'\n+ '</html>\\n'.format(session[CSRF_KEY]))\n+\n+ print('Got past GET')\ntry:\ntoken = oauth2.rfc6749.tokens.get_token_from_header(request)\nexcept AttributeError:\n@@ -184,9 +203,15 @@ def validate_api_token():\nreturn abort(\nHTTP_STATUS_CODE_UNAUTHORIZED, 'Request not authenticated.')\n- data = request.data\n+ id_token = None\n+ data = request.form\n+ if data:\nid_token = data.get('id_token')\n+\nif not id_token:\n+ print(data)\n+ print(request.args)\n+ print(request.__dict__)\nreturn abort(\nHTTP_STATUS_CODE_UNAUTHORIZED, 'No ID token supplied.')\n" } ]
Python
Apache License 2.0
google/timesketch
Making more changes.
263,133
14.11.2019 13:37:43
0
26a3f3bd66fa33779ef1a2c46f86d3f601778bc8
Adding a new issuer
[ { "change_type": "MODIFY", "old_path": "data/timesketch.conf", "new_path": "data/timesketch.conf", "diff": "@@ -82,7 +82,7 @@ GOOGLE_IAP_AUDIENCE = '/projects/{}/global/backendServices/{}'.format(\n)\nGOOGLE_IAP_ALGORITHM = 'ES256'\n-GOOGLE_IAP_ISSUER = 'https://cloud.google.com/iap'\n+GOOGLE_IAP_ISSUER = 'https://cloud.google.com/iap,https://accounts.google.com'\nGOOGLE_IAP_PUBLIC_KEY_URL = 'https://www.gstatic.com/iap/verify/public_key'\n#-------------------------------------------------------------------------------\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a new issuer
263,133
14.11.2019 14:43:35
0
c448b096efb58f39131c480ec96ddb21e3222d81
Changing expected issuer.
[ { "change_type": "MODIFY", "old_path": "data/timesketch.conf", "new_path": "data/timesketch.conf", "diff": "@@ -82,7 +82,7 @@ GOOGLE_IAP_AUDIENCE = '/projects/{}/global/backendServices/{}'.format(\n)\nGOOGLE_IAP_ALGORITHM = 'ES256'\n-GOOGLE_IAP_ISSUER = 'https://cloud.google.com/iap,https://accounts.google.com'\n+GOOGLE_IAP_ISSUER = 'https://cloud.google.com/iap'\nGOOGLE_IAP_PUBLIC_KEY_URL = 'https://www.gstatic.com/iap/verify/public_key'\n#-------------------------------------------------------------------------------\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/google_auth.py", "new_path": "timesketch/lib/google_auth.py", "diff": "@@ -229,7 +229,6 @@ def validate_jwt(decoded_jwt, expected_issuer, expected_domain=None):\nRaises:\nJwtValidationError: If unable to validate the JWT.\n\"\"\"\n- expected_issuers = expected_issuer.split(',')\n# Make sure the token is not created in the future or has expired.\ntry:\nnow = int(time.time())\n@@ -251,7 +250,7 @@ def validate_jwt(decoded_jwt, expected_issuer, expected_domain=None):\n# Check that the issuer of the token is correct.\ntry:\nissuer = decoded_jwt['iss']\n- if issuer not in expected_issuers:\n+ if issuer != expected_issuer:\nraise JwtValidationError('Wrong issuer: {}'.format(issuer))\nexcept KeyError:\nraise JwtValidationError('Missing issuer')\n" }, { "change_type": "MODIFY", "old_path": "timesketch/views/auth.py", "new_path": "timesketch/views/auth.py", "diff": "@@ -230,7 +230,14 @@ def validate_api_token():\nHTTP_STATUS_CODE_UNAUTHORIZED,\n'Auth token and client tokens don\\'t match, email differs.')\n- expected_issuer = current_app.config.get('GOOGLE_IAP_ISSUER')\n+ try:\n+ discovery_document = get_oauth2_discovery_document()\n+ except DiscoveryDocumentError as e:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to discover document, with error: {0!s}'.format(e))\n+\n+ expected_issuer = discovery_document['issuer']\ntry:\nvalidate_jwt(token_json, expected_issuer)\nexcept (ImportError, NameError, UnboundLocalError):\n" } ]
Python
Apache License 2.0
google/timesketch
Changing expected issuer.
263,133
18.11.2019 12:30:32
0
ed7854106d15334ce7a219411086d6774b235637
Adding a server to catch OAUTH flow.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -144,14 +144,21 @@ class TimesketchApi(object):\n'referer': self._host_uri\n})\n- def _create_oauth_session(self, client_id, client_secret, skip_open=False):\n+ def _create_oauth_session(\n+ self, client_id='', client_secret='', client_secrets_file=None,\n+ run_server=True, skip_open=False):\n\"\"\"Return an OAuth session.\nArgs:\nclient_id: The client ID if OAUTH auth is used.\nclient_secret: The OAUTH client secret if OAUTH is used.\n- skip_open: If set to True then an auth URL will be printed, instead\n- of presenting an option to open a browser window.\n+ client_secrets_file: Path to the JSON file that contains the client\n+ secrets, in the client_secrets format.\n+ run_server: A boolean, if set to true (default) a web server is\n+ run to catch the OAUTH request and response.\n+ skip_open: A booelan, if set to True (defaults to False) an\n+ authorization URL is printed on the screen to visit. This is\n+ only valid if run_server is set to False.\nReturn:\nsession: Instance of requests.Session.\n@@ -159,20 +166,33 @@ class TimesketchApi(object):\nRaises:\nRuntimeError: if unable to log in to the application.\n\"\"\"\n+ if client_secrets_file:\n+ if not os.path.isfile(client_secrets_file):\n+ raise RuntimeError(\n+ 'Unable to log in, client secret files does not exist.')\n+ flow = googleauth_flow.InstalledAppFlow.from_client_secrets_file(\n+ client_secrets_file, scopes=self.DEFAULT_OAUTH_SCOPE)\n+ else:\n+ provider_url = self.DEFAULT_OAUTH_PROVIDER_URL\nclient_config = {\n'installed': {\n'client_id': client_id,\n'client_secret': client_secret,\n'auth_uri': self.DEFAULT_OAUTH_AUTH_URL,\n'token_uri': self.DEFAULT_OAUTH_TOKEN_URL,\n- 'auth_provider_x509_cert_url': self.DEFAULT_OAUTH_PROVIDER_URL,\n+ 'auth_provider_x509_cert_url': provider_url,\n'redirect_uris': [self.DEFAULT_OAUTH_OOB_URL],\n},\n}\nflow = googleauth_flow.InstalledAppFlow.from_client_config(\nclient_config, self.DEFAULT_OAUTH_SCOPE)\n+\nflow.redirect_uri = self.DEFAULT_OAUTH_OOB_URL\n+\n+ if run_server:\n+ _ = flow.run_local_server()\n+ else:\nauth_url, _ = flow.authorization_url(prompt='select_account')\nif skip_open:\n@@ -184,12 +204,12 @@ class TimesketchApi(object):\nwebbrowser.open(auth_url)\nelse:\nprint(\n- 'Need to manually visit URL to authenticate: {0:s}'.format(\n- auth_url))\n+ 'Need to manually visit URL to authenticate: '\n+ '{0:s}'.format(auth_url))\ncode = input('Enter the token code: ')\n-\n_ = flow.fetch_token(code=code)\n+\nsession = flow.authorized_session()\nself._flow = flow\nself._credentials = flow.credentials\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a server to catch OAUTH flow.
263,133
18.11.2019 13:10:24
0
2e6d1b81cb4c2f7bbb569b4b71bf372af9d5ee3a
Adding an auto generated code verifier
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -172,7 +172,8 @@ class TimesketchApi(object):\nraise RuntimeError(\n'Unable to log in, client secret files does not exist.')\nflow = googleauth_flow.InstalledAppFlow.from_client_secrets_file(\n- client_secrets_file, scopes=self.DEFAULT_OAUTH_SCOPE)\n+ client_secrets_file, scopes=self.DEFAULT_OAUTH_SCOPE,\n+ autogenerate_code_verifier=True)\nelse:\nprovider_url = self.DEFAULT_OAUTH_PROVIDER_URL\nclient_config = {\n@@ -187,7 +188,8 @@ class TimesketchApi(object):\n}\nflow = googleauth_flow.InstalledAppFlow.from_client_config(\n- client_config, self.DEFAULT_OAUTH_SCOPE)\n+ client_config, self.DEFAULT_OAUTH_SCOPE,\n+ autogenerate_code_verifier=True)\nflow.redirect_uri = self.DEFAULT_OAUTH_OOB_URL\n" } ]
Python
Apache License 2.0
google/timesketch
Adding an auto generated code verifier
263,133
19.11.2019 15:21:57
0
3f994717c1183feda6d14b6ae1f5ca28ce525bbb
Adding description and chart titles for aggregation.
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -988,6 +988,8 @@ class AggregationExploreResource(ResourceMixin, Resource):\nresult_obj = aggregator.run(**aggregator_parameters)\ntime_after = time.time()\n+ aggregator_description = aggregator.describe\n+\nbuckets = result_obj.to_dict()\nbuckets['buckets'] = buckets.pop('values')\nresult = {\n@@ -997,12 +999,14 @@ class AggregationExploreResource(ResourceMixin, Resource):\n}\nmeta = {\n'method': 'aggregator_run',\n- 'name': aggregator_name,\n+ 'name': aggregator_description.get('name'),\n+ 'description': aggregator_description.get('description'),\n'es_time': time_after - time_before,\n}\nif chart_type:\n- meta['vega_spec'] = result_obj.to_chart(chart_name=chart_type)\n+ meta['vega_spec'] = result_obj.to_chart(\n+ chart_name=chart_type, chart_title=aggregator.chart_title)\nelif aggregation_dsl:\n# pylint: disable=unexpected-keyword-arg\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/bucket.py", "new_path": "timesketch/lib/aggregators/bucket.py", "diff": "@@ -23,6 +23,7 @@ class TermsAggregation(interface.BaseAggregator):\n\"\"\"Terms Bucket Aggregation.\"\"\"\nNAME = 'field_bucket'\n+ DESCRIPTION = 'Aggregating values of a particular field'\nSUPPORTED_CHARTS = frozenset(['barchart', 'hbarchart'])\n@@ -49,6 +50,24 @@ class TermsAggregation(interface.BaseAggregator):\n}\n]\n+ def __init__(self, sketch_id=None, index=None):\n+ \"\"\"Initialize the aggregator object.\n+\n+ Args:\n+ sketch_id: Sketch ID.\n+ index: List of elasticsearch index names.\n+ \"\"\"\n+ super(TermsAggregation, self).__init__(\n+ sketch_id=sketch_id, index=index)\n+ self.field = ''\n+\n+ @property\n+ def chart_title(self):\n+ \"\"\"Returns a title for the chart.\"\"\"\n+ if self.field:\n+ return 'Top results for \"{0:s}\"'.format(self.field)\n+ return 'Top results for an unknown field'\n+\n# pylint: disable=arguments-differ\ndef run(self, field, limit=10):\n\"\"\"Run the aggregation.\n@@ -60,6 +79,7 @@ class TermsAggregation(interface.BaseAggregator):\nReturns:\nInstance of interface.AggregationResult with aggregation result.\n\"\"\"\n+ self.field = field\n# Encoding information for Vega-Lite.\nencoding = {\n'x': {\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/interface.py", "new_path": "timesketch/lib/aggregators/interface.py", "diff": "@@ -64,11 +64,14 @@ class AggregationResult(object):\n\"\"\"\nreturn pandas.DataFrame(self.values)\n- def to_chart(self, chart_name, as_html=False, interactive=False):\n+ def to_chart(\n+ self, chart_name, chart_title='', as_html=False,\n+ interactive=False):\n\"\"\"Encode aggregation result as Vega-Lite chart.\nArgs:\nchart_name: Name of chart as string.\n+ chart_title: The title of the chart.\nas_html: Boolean indicating if chart should be returned in HTML.\ninteractive: Boolean indicating if chart should be interactive.\n@@ -84,7 +87,7 @@ class AggregationResult(object):\nraise RuntimeError('No such chart type: {0:s}'.format(chart_name))\nchart_data = self.to_dict(encoding=True)\n- chart_object = chart_class(chart_data)\n+ chart_object = chart_class(chart_data, title=chart_title)\nchart = chart_object.generate()\nif interactive:\n@@ -101,6 +104,10 @@ class BaseAggregator(object):\n# Name that the aggregator will be registered as.\nNAME = 'name'\n+ # Describe what the aggregator does, this will be visible in the UI\n+ # among other places.\n+ DESCRIPTION = ''\n+\n# Used as hints to the frontend UI in order to render input forms.\nFORM_FIELDS = {}\n@@ -127,6 +134,19 @@ class BaseAggregator(object):\nactive_timelines = self.sketch.active_timelines\nself.index = [t.searchindex.index_name for t in active_timelines]\n+ @property\n+ def chart_title(self):\n+ \"\"\"Returns a title for the chart.\"\"\"\n+ raise NotImplementedError\n+\n+ @property\n+ def describe(self):\n+ \"\"\"Returns dict with name as well as a description of aggregator.\"\"\"\n+ return {\n+ 'name': self.NAME,\n+ 'description': self.DESCRIPTION,\n+ }\n+\ndef elastic_aggregation(self, aggregation_spec):\n\"\"\"Helper method to execute aggregation in Elasticsearch.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/term.py", "new_path": "timesketch/lib/aggregators/term.py", "diff": "@@ -77,6 +77,7 @@ class FilteredTermsAggregation(interface.BaseAggregator):\n\"\"\"Query Filter Term Aggregation.\"\"\"\nNAME = 'query_bucket'\n+ DESCRIPTION = 'Aggregating values of a field after applying a filter'\nSUPPORTED_CHARTS = frozenset(['barchart', 'hbarchart'])\n@@ -108,6 +109,24 @@ class FilteredTermsAggregation(interface.BaseAggregator):\n}\n]\n+ def __init__(self, sketch_id=None, index=None):\n+ \"\"\"Initialize the aggregator object.\n+\n+ Args:\n+ sketch_id: Sketch ID.\n+ index: List of elasticsearch index names.\n+ \"\"\"\n+ super(FilteredTermsAggregation, self).__init__(\n+ sketch_id=sketch_id, index=index)\n+ self.field = ''\n+\n+ @property\n+ def chart_title(self):\n+ \"\"\"Returns a title for the chart.\"\"\"\n+ if self.field:\n+ return 'Top filtered results for \"{0:s}\"'.format(self.field)\n+ return 'Top results for an unknown field after filtering'\n+\n# pylint: disable=arguments-differ\ndef run(self, field, query_string='', query_dsl=''):\n\"\"\"Run the aggregation.\n@@ -130,6 +149,7 @@ class FilteredTermsAggregation(interface.BaseAggregator):\nif not (query_string or query_dsl):\nraise ValueError('Both query_string and query_dsl are missing')\n+ self.field = field\naggregation_spec = get_spec(\nfield=field, query=query_string, query_dsl=query_dsl)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/charts/barchart.py", "new_path": "timesketch/lib/charts/barchart.py", "diff": "@@ -32,6 +32,9 @@ class BarChart(interface.BaseChart):\nReturns:\nInstance of altair.Chart\n\"\"\"\n+ if self.chart_title:\n+ chart = alt.Chart().mark_bar().properties(title=self.chart_title)\n+ else:\nchart = alt.Chart().mark_bar()\nchart.encoding = alt.FacetedEncoding.from_dict(self.encoding)\nchart.data = self.values\n@@ -53,6 +56,10 @@ class HorizontalBarChart(interface.BaseChart):\nencoding['x'] = self.encoding['y']\nencoding['y'] = self.encoding['x']\n+ if self.chart_title:\n+ bars = alt.Chart(self.values).mark_bar().properties(\n+ title=self.chart_title)\n+ else:\nbars = alt.Chart(self.values).mark_bar()\nbars.encoding = alt.FacetedEncoding.from_dict(encoding)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/charts/interface.py", "new_path": "timesketch/lib/charts/interface.py", "diff": "@@ -25,11 +25,12 @@ class BaseChart(object):\n# Name that the chart will be registered as.\nNAME = 'name'\n- def __init__(self, data):\n+ def __init__(self, data, title=''):\n\"\"\"Initialize the chart object.\nArgs:\ndata: Dictionary with list of values and dict of encoding info.\n+ title: String used for the chart title.\nRaises:\nRuntimeError if values or encoding is missing from data.\n@@ -46,6 +47,7 @@ class BaseChart(object):\nelse:\nself.values = alt.Data(values=_values)\nself.encoding = _encoding\n+ self.chart_title = title\ndef generate(self):\n\"\"\"Entry point for the chart.\"\"\"\n" } ]
Python
Apache License 2.0
google/timesketch
Adding description and chart titles for aggregation. (#1036)
263,093
22.11.2019 11:09:48
-3,600
d1e7eb29a8e86c7418e73d63038022a761791166
Set correct value in option dropdown
[ { "change_type": "MODIFY", "old_path": "timesketch/frontend/src/components/Sketch/AggregationListDropdown.vue", "new_path": "timesketch/frontend/src/components/Sketch/AggregationListDropdown.vue", "diff": "@@ -20,7 +20,7 @@ limitations under the License.\n<div class=\"select\">\n<select v-model=\"selected\" @change=\"setActiveAggregator()\">\n<option disabled value=\"\">Please select one</option>\n- <option v-for=\"(aggregator, name) in meta.aggregators\" :key=\"aggregator.id\">\n+ <option v-for=\"(aggregator, name) in meta.aggregators\" :key=\"aggregator.id\" :value=\"name\">\n{{ name }} - {{ aggregator.description }}\n</option>\n</select>\n" } ]
Python
Apache License 2.0
google/timesketch
Set correct value in option dropdown
263,133
22.11.2019 13:40:58
0
f8585298b2f9e6c79753c1eb34694e484ea69098
Forgot to remove a print statement
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch_test.py", "new_path": "api_client/python/timesketch_api_client/sketch_test.py", "diff": "@@ -51,7 +51,6 @@ class SketchTest(unittest.TestCase):\ndef test_explore(self):\n\"\"\"Tests to explore a timeline.\"\"\"\n- print('EXPL')\nresults = self.sketch.explore(query_string='description:test')\nself.assertEqual(len(results['objects']), 1)\nself.assertIsInstance(results['objects'], list)\n" } ]
Python
Apache License 2.0
google/timesketch
Forgot to remove a print statement
263,093
28.11.2019 15:10:20
-3,600
6cbe3fe46759d4e67fddd48c787089297ae0b16c
New base dev image build
[ { "change_type": "MODIFY", "old_path": "docker/development/Dockerfile", "new_path": "docker/development/Dockerfile", "diff": "# Use the latest Timesketch development base image\n-FROM timesketch/timesketch-dev-base:20190603\n+FROM timesketch/timesketch-dev-base:20191128\n# Install dependencies for Timesketch\nCOPY requirements.txt /timesketch-requirements.txt\n" } ]
Python
Apache License 2.0
google/timesketch
New base dev image build
263,093
07.12.2019 02:32:11
-3,600
9136334628cb5a789d22fcfd4f3d6fd19ce66f3b
Enable new UI
[ { "change_type": "MODIFY", "old_path": "timesketch/__init__.py", "new_path": "timesketch/__init__.py", "diff": "@@ -39,7 +39,7 @@ from timesketch.views.auth import auth_views\nfrom timesketch.views.spa import spa_views\n# Set to true to use the new Vue.js based frontend.\n-USE_NEW_FRONTEND = False\n+USE_NEW_FRONTEND = True\ndef create_app(config=None):\n" } ]
Python
Apache License 2.0
google/timesketch
Enable new UI
263,096
13.12.2019 22:13:30
-3,600
e1bc479f431eedab4087f92f2db4ba9087296b6d
Remove vagrant from the readme as per Vagrant support was dropped, so should not be in the readme
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -20,7 +20,6 @@ Timesketch is an open source tool for collaborative forensic timeline analysis.\n#### Installation\n* [Install Timesketch manually](docs/Installation.md)\n-* [Use Vagrant](vagrant)\n* [Use Docker](docker)\n* [Upgrade from existing installation](docs/Upgrading.md)\n" } ]
Python
Apache License 2.0
google/timesketch
Remove vagrant from the readme (#1058) as per https://github.com/google/timesketch/pull/979 Vagrant support was dropped, so should not be in the readme
263,093
18.12.2019 11:04:13
-3,600
83688dd2657221fae077694172731ba507161e5a
Change default location for config file
[ { "change_type": "MODIFY", "old_path": "config/dpkg/timesketch-server.timesketch.default", "new_path": "config/dpkg/timesketch-server.timesketch.default", "diff": "# Timesketch configuration\n#\n-# The default location for this configuration file is in /etc/timesketch.conf\n+# The default location for this configuration file is in /etc/timesketch/timesketch.conf\n# If you put it somewhere else you can pass the path to tsctl\n# Example:\n#\n" }, { "change_type": "MODIFY", "old_path": "docker/Dockerfile", "new_path": "docker/Dockerfile", "diff": "@@ -34,10 +34,9 @@ RUN cd /tmp/timesketch && yarn install && yarn run build\nRUN sed -i -e '/pyyaml/d' /tmp/timesketch/requirements.txt\nRUN pip3 install /tmp/timesketch/\n-# Copy the Timesketch configuration file into /etc\n-RUN cp /tmp/timesketch/data/timesketch.conf /etc\n# Copy Timesketch config files into /etc/timesketch\nRUN mkdir /etc/timesketch\n+RUN cp /tmp/timesketch/data/timesketch.conf /etc/timesketch/\nRUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\n# Copy the entrypoint script into the container\n" }, { "change_type": "MODIFY", "old_path": "docker/development/docker-entrypoint.sh", "new_path": "docker/development/docker-entrypoint.sh", "diff": "@@ -8,19 +8,19 @@ if [ \"$1\" = 'timesketch' ]; then\n# Copy config files\nmkdir /etc/timesketch\n- cp /usr/local/src/timesketch/data/timesketch.conf /etc\n+ cp /usr/local/src/timesketch/data/timesketch.conf /etc/timesketch/\ncp /usr/local/src/timesketch/data/features.yaml /etc/timesketch/\n- # Set SECRET_KEY in /etc/timesketch.conf if it isn't already set\n- if grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\n+ # Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\n+ if grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\nOPENSSL_RAND=$( openssl rand -base64 32 )\n# Using the pound sign as a delimiter to avoid problems with / being output from openssl\n- sed -i 's#SECRET_KEY = \\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = \\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch.conf\n+ sed -i 's#SECRET_KEY = \\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = \\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch/timesketch.conf\nfi\n# Set up the Postgres connection\nif [ $POSTGRES_USER ] && [ $POSTGRES_PASSWORD ] && [ $POSTGRES_ADDRESS ] && [ $POSTGRES_PORT ]; then\n- sed -i 's#postgresql://<USERNAME>:<PASSWORD>@localhost#postgresql://'$POSTGRES_USER':'$POSTGRES_PASSWORD'@'$POSTGRES_ADDRESS':'$POSTGRES_PORT'#' /etc/timesketch.conf\n+ sed -i 's#postgresql://<USERNAME>:<PASSWORD>@localhost#postgresql://'$POSTGRES_USER':'$POSTGRES_PASSWORD'@'$POSTGRES_ADDRESS':'$POSTGRES_PORT'#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_ADDRESS, and POSTGRES_PORT environment variables\"\n@@ -29,8 +29,8 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Elastic connection\nif [ $ELASTIC_ADDRESS ] && [ $ELASTIC_PORT ]; then\n- sed -i 's#ELASTIC_HOST = \\x27127.0.0.1\\x27#ELASTIC_HOST = \\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch.conf\n- sed -i 's#ELASTIC_PORT = 9200#ELASTIC_PORT = '$ELASTIC_PORT'#' /etc/timesketch.conf\n+ sed -i 's#ELASTIC_HOST = \\x27127.0.0.1\\x27#ELASTIC_HOST = \\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch/timesketch.conf\n+ sed -i 's#ELASTIC_PORT = 9200#ELASTIC_PORT = '$ELASTIC_PORT'#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the ELASTIC_ADDRESS and ELASTIC_PORT environment variables\"\n@@ -38,9 +38,9 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Redis connection\nif [ $REDIS_ADDRESS ] && [ $REDIS_PORT ]; then\n- sed -i 's#UPLOAD_ENABLED = False#UPLOAD_ENABLED = True#' /etc/timesketch.conf\n- sed -i 's#^CELERY_BROKER_URL =.*#CELERY_BROKER_URL = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch.conf\n- sed -i 's#^CELERY_RESULT_BACKEND =.*#CELERY_RESULT_BACKEND = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch.conf\n+ sed -i 's#UPLOAD_ENABLED = False#UPLOAD_ENABLED = True#' /etc/timesketch/timesketch.conf\n+ sed -i 's#^CELERY_BROKER_URL =.*#CELERY_BROKER_URL = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch/timesketch.conf\n+ sed -i 's#^CELERY_RESULT_BACKEND =.*#CELERY_RESULT_BACKEND = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the REDIS_ADDRESS and REDIS_PORT environment variables\"\n@@ -48,21 +48,21 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Neo4j connection\nif [ $NEO4J_ADDRESS ] && [ $NEO4J_PORT ]; then\n- sed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch.conf\n- sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch.conf\n- sed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch.conf\n+ sed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch/timesketch.conf\n+ sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch/timesketch.conf\n+ sed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the NEO4J_ADDRESS and NEO4J_PORT environment variables if you want graph support\"\nfi\n# Enable debug for the development server\n- sed -i s/\"DEBUG = False\"/\"DEBUG = True\"/ /etc/timesketch.conf\n+ sed -i s/\"DEBUG = False\"/\"DEBUG = True\"/ /etc/timesketch/timesketch.conf\n# Enable index and sketch analyzers\n- sed -i s/\"ENABLE_INDEX_ANALYZERS = False\"/\"ENABLE_INDEX_ANALYZERS = True\"/ /etc/timesketch.conf\n- sed -i s/\"ENABLE_SKETCH_ANALYZERS = False\"/\"ENABLE_SKETCH_ANALYZERS = True\"/ /etc/timesketch.conf\n- sed -i s/\"ENABLE_EXPERIMENTAL_UI = False\"/\"ENABLE_EXPERIMENTAL_UI = True\"/ /etc/timesketch.conf\n+ sed -i s/\"ENABLE_INDEX_ANALYZERS = False\"/\"ENABLE_INDEX_ANALYZERS = True\"/ /etc/timesketch/timesketch.conf\n+ sed -i s/\"ENABLE_SKETCH_ANALYZERS = False\"/\"ENABLE_SKETCH_ANALYZERS = True\"/ /etc/timesketch/timesketch.conf\n+ sed -i s/\"ENABLE_EXPERIMENTAL_UI = False\"/\"ENABLE_EXPERIMENTAL_UI = True\"/ /etc/timesketch/timesketch.conf\n# Add web user\ntsctl add_user --username \"${TIMESKETCH_USER}\" --password \"${TIMESKETCH_USER}\"\n" }, { "change_type": "MODIFY", "old_path": "docker/docker-entrypoint.sh", "new_path": "docker/docker-entrypoint.sh", "diff": "# Run the container the default way\nif [ \"$1\" = 'timesketch' ]; then\n- # Set SECRET_KEY in /etc/timesketch.conf if it isn't already set\n- if grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch.conf; then\n+ # Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\n+ if grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\nOPENSSL_RAND=$( openssl rand -base64 32 )\n# Using the pound sign as a delimiter to avoid problems with / being output from openssl\n- sed -i 's#SECRET_KEY = \\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = \\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch.conf\n+ sed -i 's#SECRET_KEY = \\x27\\x3CKEY_GOES_HERE\\x3E\\x27#SECRET_KEY = \\x27'$OPENSSL_RAND'\\x27#' /etc/timesketch/timesketch.conf\nfi\n# Set up the Postgres connection\nif [ $POSTGRES_USER ] && [ $POSTGRES_PASSWORD ] && [ $POSTGRES_ADDRESS ] && [ $POSTGRES_PORT ]; then\n- sed -i 's#postgresql://<USERNAME>:<PASSWORD>@localhost#postgresql://'$POSTGRES_USER':'$POSTGRES_PASSWORD'@'$POSTGRES_ADDRESS':'$POSTGRES_PORT'#' /etc/timesketch.conf\n+ sed -i 's#postgresql://<USERNAME>:<PASSWORD>@localhost#postgresql://'$POSTGRES_USER':'$POSTGRES_PASSWORD'@'$POSTGRES_ADDRESS':'$POSTGRES_PORT'#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_ADDRESS, and POSTGRES_PORT environment variables\"\n@@ -20,8 +20,8 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Elastic connection\nif [ $ELASTIC_ADDRESS ] && [ $ELASTIC_PORT ]; then\n- sed -i 's#ELASTIC_HOST = \\x27127.0.0.1\\x27#ELASTIC_HOST = \\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch.conf\n- sed -i 's#ELASTIC_PORT = 9200#ELASTIC_PORT = '$ELASTIC_PORT'#' /etc/timesketch.conf\n+ sed -i 's#ELASTIC_HOST = \\x27127.0.0.1\\x27#ELASTIC_HOST = \\x27'$ELASTIC_ADDRESS'\\x27#' /etc/timesketch/timesketch.conf\n+ sed -i 's#ELASTIC_PORT = 9200#ELASTIC_PORT = '$ELASTIC_PORT'#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the ELASTIC_ADDRESS and ELASTIC_PORT environment variables\"\n@@ -29,9 +29,9 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Redis connection\nif [ $REDIS_ADDRESS ] && [ $REDIS_PORT ]; then\n- sed -i 's#UPLOAD_ENABLED = False#UPLOAD_ENABLED = True#' /etc/timesketch.conf\n- sed -i 's#^CELERY_BROKER_URL =.*#CELERY_BROKER_URL = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch.conf\n- sed -i 's#^CELERY_RESULT_BACKEND =.*#CELERY_RESULT_BACKEND = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch.conf\n+ sed -i 's#UPLOAD_ENABLED = False#UPLOAD_ENABLED = True#' /etc/timesketch/timesketch.conf\n+ sed -i 's#^CELERY_BROKER_URL =.*#CELERY_BROKER_URL = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch/timesketch.conf\n+ sed -i 's#^CELERY_RESULT_BACKEND =.*#CELERY_RESULT_BACKEND = \\x27redis://'$REDIS_ADDRESS':'$REDIS_PORT'\\x27#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the REDIS_ADDRESS and REDIS_PORT environment variables\"\n@@ -39,9 +39,9 @@ if [ \"$1\" = 'timesketch' ]; then\n# Set up the Neo4j connection\nif [ $NEO4J_ADDRESS ] && [ $NEO4J_PORT ]; then\n- sed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch.conf\n- sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch.conf\n- sed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch.conf\n+ sed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch/timesketch.conf\n+ sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch/timesketch.conf\n+ sed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch/timesketch.conf\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the NEO4J_ADDRESS and NEO4J_PORT environment variables if you want graph support\"\n" }, { "change_type": "MODIFY", "old_path": "docs/EnablePlasoUpload.md", "new_path": "docs/EnablePlasoUpload.md", "diff": "@@ -18,7 +18,7 @@ https://github.com/log2timeline/plaso/wiki/Ubuntu-Packaged-Release\n$ sudo apt-get install redis-server\n-**Configure Timesketch** (/etc/timesketch.conf)\n+**Configure Timesketch** (/etc/timesketch/timesketch.conf)\nUPLOAD_ENABLED = True\nUPLOAD_FOLDER = u'/path/to/where/timesketch/can/write/files'\n" }, { "change_type": "MODIFY", "old_path": "docs/Installation.md", "new_path": "docs/Installation.md", "diff": "@@ -67,12 +67,13 @@ Then install Timesketch itself:\n**Configure Timesketch**\n-Copy the configuration file to `/etc` and configure it. The file is well commented and it should be pretty straight forward.\n+Copy the configuration file to `/etc/timesketch/` and configure it. The file is well commented and it should be pretty straight forward.\n- $ sudo cp /usr/local/share/timesketch/timesketch.conf /etc/\n- $ sudo chmod 600 /etc/timesketch.conf\n+ $ mkdir /etc/timesketch\n+ $ sudo cp /usr/local/share/timesketch/timesketch.conf /etc/timesketch/\n+ $ sudo chmod 600 /etc/timesketch/timesketch.conf\n-Generate a secret key and configure `SECRET_KEY` in `/etc/timesketch.conf`\n+Generate a secret key and configure `SECRET_KEY` in `/etc/timesketch/timesketch.conf`\n$ openssl rand -base64 32\n" }, { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "@@ -45,7 +45,7 @@ Parameters:\nExample\n```\n-tsctl runserver -c /etc/timesketch.conf\n+tsctl runserver -c /etc/timesketch/timesketch.conf\n```\n" }, { "change_type": "MODIFY", "old_path": "timesketch/__init__.py", "new_path": "timesketch/__init__.py", "diff": "@@ -67,7 +67,14 @@ def create_app(config=None):\n)\nif not config:\n- config = '/etc/timesketch.conf'\n+ # Where to find the config file\n+ default_path = '/etc/timesketch/timesketch.conf'\n+ # Fall back to legacy location of the config file\n+ legacy_path = '/etc/timesketch.conf'\n+ if os.path.isfile(default_path):\n+ config = default_path\n+ else:\n+ config = legacy_path\nif isinstance(config, six.text_type):\nos.environ['TIMESKETCH_SETTINGS'] = config\n" }, { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -469,7 +469,7 @@ def main():\n'-c',\n'--config',\ndest='config',\n- default='/etc/timesketch.conf',\n+ default='/etc/timesketch/timesketch.conf',\nrequired=False)\nshell_manager.run()\n" } ]
Python
Apache License 2.0
google/timesketch
Change default location for config file
263,093
20.12.2019 10:27:58
-3,600
374228d867e0c8d2c7ab332c9667a71151fcd58e
Don't exit if Plaso is not installed
[ { "change_type": "MODIFY", "old_path": "timesketch/__init__.py", "new_path": "timesketch/__init__.py", "diff": "@@ -99,10 +99,9 @@ def create_app(config=None):\nif app.config['UPLOAD_ENABLED']:\ntry:\nfrom plaso import __version__ as plaso_version\n+ app.config['PLASO_VERSION'] = plaso_version\nexcept ImportError:\nsys.stderr.write('Upload is enabled, but Plaso is not installed.')\n- sys.exit()\n- app.config['PLASO_VERSION'] = plaso_version\n# Setup the database.\nconfigure_engine(app.config['SQLALCHEMY_DATABASE_URI'])\n" } ]
Python
Apache License 2.0
google/timesketch
Don't exit if Plaso is not installed
263,093
20.12.2019 10:29:35
-3,600
a71b588023d9d6935005b41f0f90d8791d2c8a81
Always use HTTPS for OIDC redirects
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/google_auth.py", "new_path": "timesketch/lib/google_auth.py", "diff": "@@ -122,7 +122,11 @@ def get_oauth2_authorize_url(hosted_domain=None):\n\"\"\"\ncsrf_token = _generate_random_token()\nnonce = _generate_random_token()\n- redirect_uri = url_for('user_views.google_openid_connect', _external=True)\n+ redirect_uri = url_for(\n+ 'user_views.google_openid_connect',\n+ _scheme='https',\n+ _external=True\n+ )\nscopes = ('openid', 'email', 'profile')\n# Add the generated CSRF token to the client session for later validation.\n@@ -160,7 +164,11 @@ def get_encoded_jwt_over_https(code):\n\"\"\"\ndiscovery_document = get_oauth2_discovery_document()\n- redirect_uri = url_for('user_views.google_openid_connect', _external=True)\n+ redirect_uri = url_for(\n+ 'user_views.google_openid_connect',\n+ _scheme='https',\n+ _external=True\n+ )\npost_data = {\n'code': code,\n'client_id': current_app.config.get('GOOGLE_OIDC_CLIENT_ID'),\n" } ]
Python
Apache License 2.0
google/timesketch
Always use HTTPS for OIDC redirects
263,118
03.01.2020 11:20:08
-3,600
267744b2a043575af8651146031bacb56cda7e73
Run timesketch from the /tmp directory
[ { "change_type": "MODIFY", "old_path": "docker/docker-entrypoint.sh", "new_path": "docker/docker-entrypoint.sh", "diff": "@@ -62,6 +62,7 @@ if [ \"$1\" = 'timesketch' ]; then\ntsctl add_user --username \"$TIMESKETCH_USER\" --password \"$TIMESKETCH_PASSWORD\"\n# Run the Timesketch server (without SSL)\n+ cd /tmp\nexec `bash -c \"/usr/local/bin/celery -A timesketch.lib.tasks worker --uid nobody --loglevel info &\\\ngunicorn -b 0.0.0.0:80 --access-logfile - --error-logfile - --log-level info --timeout 120 timesketch.wsgi:application\"`\nfi\n" } ]
Python
Apache License 2.0
google/timesketch
Run timesketch from the /tmp directory (#1067)
263,096
03.01.2020 11:34:21
-3,600
5c9ce3f8b92e3efc4352fb34b227410bda46ac9a
Mention the correct slack channel The timesketch slack channel afaik is no longer in use.
[ { "change_type": "MODIFY", "old_path": "docs/Community-Guide.md", "new_path": "docs/Community-Guide.md", "diff": "@@ -7,7 +7,7 @@ We have a Timesketch channel (#timesketch) on the Freenode network.\nUse your favorite IRC client or try the [Freenode web based IRC client](http://webchat.freenode.net/).\n### Slack community\n-Join the [Timesketch Slack community](https://timesketch.slack.com/) by sending an email to get-slack-invite@timesketch.org.\n+Join the [DFIR Timesketch Slack community](https://open-source-dfir.slack.com/) by sending an email to get-slack-invite@timesketch.org.\nYou will get an invite in your inbox as soon as possible.\n**Why do I need to email you to get access to the Slack community?**\n" } ]
Python
Apache License 2.0
google/timesketch
Mention the correct slack channel (#1069) The timesketch slack channel afaik is no longer in use. Co-authored-by: Johan Berggren <jberggren@gmail.com>
263,096
03.01.2020 11:40:15
-3,600
40183fd33af0cd5f78d073c3cae155ae1d7f109c
Small update to dev docker readme I found it useful to write the container id to variable...
[ { "change_type": "MODIFY", "old_path": "docker/development/README.md", "new_path": "docker/development/README.md", "diff": "@@ -15,6 +15,15 @@ $ CONTAINER_ID=\"$(sudo docker container list -f name=development_timesketch -q)\"\n```\nIn the output look for CONTAINER ID for the timesketch container\n+To write the ID to a variable, use:\n+```\n+export CONTAINER_ID=\"$(sudo docker container list -f name=development_timesketch -q)\"\n+```\n+and test with\n+```\n+echo $CONTAINER_ID\n+```\n+\n### Start a celery container shell\n```\n$ sudo docker exec -it $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n" } ]
Python
Apache License 2.0
google/timesketch
Small update to dev docker readme (#1070) I found it useful to write the container id to variable... Co-authored-by: Johan Berggren <jberggren@gmail.com>
263,093
07.01.2020 15:12:32
-3,600
aefda06471a033cd1d3a9f5864dbc5677caa47f4
Use PyPi to install test containers
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -11,7 +11,7 @@ matrix:\nservices:\n- docker\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 2.7\"\n- env: UBUNTU_VERSION=\"18.04\"\n+ env: [MODE=\"pypi\", UBUNTU_VERSION=\"18.04\"]\nos: linux\ndist: xenial\nsudo: required\n@@ -21,7 +21,7 @@ matrix:\nservices:\n- docker\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6\"\n- env: UBUNTU_VERSION=\"18.04\"\n+ env: [MODE=\"pypi\", UBUNTU_VERSION=\"18.04\"]\nos: linux\ndist: xenial\nsudo: required\n" }, { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "@@ -11,8 +11,8 @@ DPKG_PYTHON3_TEST_DEPENDENCIES=\"python3-distutils python3-flask-testing python3-\n# Exit on error.\nset -e;\n-if test -n \"${UBUNTU_VERSION}\";\n-then\n+#if test -n \"${UBUNTU_VERSION}\";\n+if test ${MODE} = \"dpkg\"; then\nCONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\ndocker pull ubuntu:${UBUNTU_VERSION};\ndocker run --name=${CONTAINER_NAME} --detach -i ubuntu:${UBUNTU_VERSION};\n@@ -50,6 +50,10 @@ then\ndocker exec -e \"DEBIAN_FRONTEND=noninteractive\" ${CONTAINER_NAME} sh -c \"apt-get install -y ${DPKG_PACKAGES}\";\ndocker cp ../timesketch ${CONTAINER_NAME}:/\n+elif test ${MODE} = \"pypi\"; then\n+ pip install -r requirements.txt;\n+ pip install -r test_requirements.txt;\n+\nelif test ${TRAVIS_OS_NAME} = \"linux\"; then\npip install -r requirements.txt;\npip install -r test_requirements.txt;\n" }, { "change_type": "MODIFY", "old_path": "config/travis/runtests.sh", "new_path": "config/travis/runtests.sh", "diff": "# Exit on error.\nset -e;\n-if test -n \"${UBUNTU_VERSION}\"; then\n+if test ${MODE} = \"dpkg\"; then\nCONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\nCONTAINER_OPTIONS=\"-e LANG=en_US.UTF-8\";\n@@ -20,6 +20,10 @@ if test -n \"${UBUNTU_VERSION}\"; then\n# Note that exec options need to be defined before the container name.\ndocker exec ${CONTAINER_OPTIONS} ${CONTAINER_NAME} sh -c \"cd timesketch && ${TEST_COMMAND}\";\n+elif test ${MODE} = \"pypi\"; then\n+ python3 ./run_tests.py\n+\nelif test \"${TRAVIS_OS_NAME}\" = \"linux\"; then\npython3 ./run_tests.py\n+\nfi\n" } ]
Python
Apache License 2.0
google/timesketch
Use PyPi to install test containers
263,093
07.01.2020 16:16:53
-3,600
1b99b28f922e1a9c909e751786467691a5fdbaaa
Remove redundant pylint travis run
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "matrix:\ninclude:\n- - name: \"Ubuntu Bionic (18.04) (Docker) Pylint with Python 3.6\"\n- env: [TARGET=\"pylint\", UBUNTU_VERSION=\"18.04\"]\n- os: linux\n- dist: xenial\n- sudo: required\n- group: edge\n- language: python\n- python: 3.6\n- services:\n- - docker\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 2.7\"\nenv: [MODE=\"pypi\", UBUNTU_VERSION=\"18.04\"]\nos: linux\n" }, { "change_type": "MODIFY", "old_path": "requirements.txt", "new_path": "requirements.txt", "diff": "alembic==1.3.2\n-altair==3.3.0\n+altair==3.3.0 # Note: Last version to support py2\ncelery==4.4.0\ncryptography==2.1.4\ndatasketch==1.5.0\n@@ -14,11 +14,11 @@ flask_sqlalchemy==2.4.1\nflask_wtf==0.14.2\ngoogle-auth==1.7.0\ngoogle_auth_oauthlib==0.4.1\n-gunicorn==19.10.0\n+gunicorn==19.10.0 # Note: Last version to support py2\nneo4jrestclient==2.1.1\n-numpy==1.16.6\n+numpy==1.16.6 # Note: Last version to support py2\noauthlib==3.1.0\n-pandas==0.24.2\n+pandas==0.24.2 # Note: Last version to support py2\nPyJWT==1.7.1\npython_dateutil==2.8.1\nPyYAML==5.3\n" }, { "change_type": "MODIFY", "old_path": "test_requirements.txt", "new_path": "test_requirements.txt", "diff": "@@ -6,4 +6,4 @@ pbr >= 4.2.0\nsix >= 1.1.0\nbeautifulsoup4 >= 4.8.2\ncoverage >= 5.0.2\n-pylint >= 1.9.5\n\\ No newline at end of file\n+pylint >= 1.9.5 # Note: Last version to support py2\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
Remove redundant pylint travis run
263,093
30.01.2020 13:04:11
-3,600
516920b9198fe91a5e90c01a2fca6d103bdaf91c
Use new frontend and remove Neo4j
[ { "change_type": "MODIFY", "old_path": "docker/Dockerfile", "new_path": "docker/Dockerfile", "diff": "@@ -6,7 +6,6 @@ RUN apt-get update && apt-get -y upgrade && apt-get -y dist-upgrade\n# Setup install environment and Timesketch dependencies\nRUN apt-get -y install apt-transport-https \\\n- curl \\\ngit \\\nlibffi-dev \\\nlsb-release \\\n@@ -14,33 +13,21 @@ RUN apt-get -y install apt-transport-https \\\npython3-pip \\\npython3-psycopg2\n-RUN curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -\n-RUN VERSION=node_8.x && \\\n- DISTRO=\"$(lsb_release -s -c)\" && \\\n- echo \"deb https://deb.nodesource.com/$VERSION $DISTRO main\" > /etc/apt/sources.list.d/nodesource.list\n-RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -\n-RUN echo \"deb https://dl.yarnpkg.com/debian/ stable main\" > /etc/apt/sources.list.d/yarn.list\n-\n# Install Plaso, nodejs and yarn.\nRUN apt-get -y install software-properties-common\nRUN add-apt-repository ppa:gift/stable && apt-get update\n-RUN apt-get update && apt-get -y install plaso-tools nodejs yarn\n+RUN apt-get update && apt-get -y install plaso-tools\n# Use Python 3 pip (pip3) to install Timesketch\n-RUN pip3 install --upgrade pip\n-ADD . /tmp/timesketch\n-RUN cd /tmp/timesketch && yarn install && yarn run build\n-# Remove pyyaml from requirements.txt to avoid conflicts with python-yaml Ubuntu package\n-RUN sed -i -e '/pyyaml/d' /tmp/timesketch/requirements.txt\n-RUN pip3 install /tmp/timesketch/\n+RUN pip3 install timesketch\n# Copy Timesketch config files into /etc/timesketch\n+ADD . /tmp/timesketch\nRUN mkdir /etc/timesketch\nRUN cp /tmp/timesketch/data/timesketch.conf /etc/timesketch/\nRUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/\n-\n# Copy the entrypoint script into the container\nCOPY docker/docker-entrypoint.sh /\nRUN chmod a+x /docker-entrypoint.sh\n" }, { "change_type": "MODIFY", "old_path": "docker/docker-compose.yml", "new_path": "docker/docker-compose.yml", "diff": "@@ -19,8 +19,6 @@ services:\n- ELASTIC_PORT=9200\n- REDIS_ADDRESS=redis\n- REDIS_PORT=6379\n- - NEO4J_ADDRESS=neo4j\n- - NEO4J_PORT=7474\n- TIMESKETCH_USER=${TIMESKETCH_USER}\n- TIMESKETCH_PASSWORD=${TIMESKETCH_PASSWORD}\nrestart: always\n@@ -59,11 +57,3 @@ services:\nrestart: always\nvolumes:\n- /var/lib/redis:/data\n-\n- neo4j:\n- image: neo4j\n- environment:\n- - NEO4J_AUTH=none\n- restart: always\n- volumes:\n- - /var/lib/neo4j/data:/var/lib/neo4j/data\n" }, { "change_type": "MODIFY", "old_path": "docker/docker-entrypoint.sh", "new_path": "docker/docker-entrypoint.sh", "diff": "@@ -37,16 +37,6 @@ if [ \"$1\" = 'timesketch' ]; then\necho \"Please pass values for the REDIS_ADDRESS and REDIS_PORT environment variables\"\nfi\n- # Set up the Neo4j connection\n- if [ $NEO4J_ADDRESS ] && [ $NEO4J_PORT ]; then\n- sed -i 's#GRAPH_BACKEND_ENABLED = False#GRAPH_BACKEND_ENABLED = True#' /etc/timesketch/timesketch.conf\n- sed -i 's#NEO4J_HOST =.*#NEO4J_HOST = \\x27'$NEO4J_ADDRESS'\\x27#' /etc/timesketch/timesketch.conf\n- sed -i 's#NEO4J_PORT =.*#NEO4J_PORT = '$NEO4J_PORT'#' /etc/timesketch/timesketch.conf\n- else\n- # Log an error since we need the above-listed environment variables\n- echo \"Please pass values for the NEO4J_ADDRESS and NEO4J_PORT environment variables if you want graph support\"\n- fi\n-\n# Set up web credentials\nif [ -z ${TIMESKETCH_USER:+x} ]; then\nTIMESKETCH_USER=\"admin\"\n" } ]
Python
Apache License 2.0
google/timesketch
Use new frontend and remove Neo4j
263,136
04.02.2020 15:25:31
-3,600
24ecf90d5c04aeddfd00408f87b6ba940c6b79aa
api_client: possibility to specify index when uploading data
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -284,7 +284,7 @@ class ImportStreamer(object):\nfilepath, delimiter=delimiter, chunksize=self._threshold):\nself.add_data_frame(chunk_frame, part_of_iter=True)\nelif file_ending == 'plaso':\n- self._sketch.upload(self._timeline_name, filepath)\n+ self._sketch.upload(self._timeline_name, filepath, self._index)\nelif file_ending == 'jsonl':\ndata_frame = None\nwith open(filepath, 'r') as fh:\n@@ -402,6 +402,10 @@ class ImportStreamer(object):\n\"\"\"Set the timeline name.\"\"\"\nself._timeline_name = name\n+ def set_index_name(self, index):\n+ \"\"\"Set the index name.\"\"\"\n+ self._index = index\n+\ndef set_timestamp_description(self, description):\n\"\"\"Set the timestamp description field.\"\"\"\nself._timestamp_desc = description\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -237,7 +237,7 @@ class Sketch(resource.BaseResource):\ntimelines.append(timeline_obj)\nreturn timelines\n- def upload(self, timeline_name, file_path):\n+ def upload(self, timeline_name, file_path, index=None):\n\"\"\"Upload a CSV, JSONL, or Plaso file to the server for indexing.\nArgs:\n@@ -249,7 +249,7 @@ class Sketch(resource.BaseResource):\n\"\"\"\nresource_url = '{0:s}/upload/'.format(self.api.api_root)\nfiles = {'file': open(file_path, 'rb')}\n- data = {'name': timeline_name, 'sketch_id': self.id}\n+ data = {'name': timeline_name, 'sketch_id': self.id, 'index_name': index}\nresponse = self.api.session.post(resource_url, files=files, data=data)\nresponse_dict = response.json()\ntimeline_dict = response_dict['objects'][0]\n" } ]
Python
Apache License 2.0
google/timesketch
api_client: possibility to specify index when uploading data
263,136
05.02.2020 10:23:57
-3,600
71f8c49867c48e8f8f3e19dbc846b26681b3493b
fix args and linter
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -243,13 +243,15 @@ class Sketch(resource.BaseResource):\nArgs:\ntimeline_name: Name of the resulting timeline.\nfile_path: Path to the file to be uploaded.\n+ index: Index name for the ES database\nReturns:\nTimeline object instance.\n\"\"\"\nresource_url = '{0:s}/upload/'.format(self.api.api_root)\nfiles = {'file': open(file_path, 'rb')}\n- data = {'name': timeline_name, 'sketch_id': self.id, 'index_name': index}\n+ data = {'name': timeline_name, 'sketch_id': self.id,\n+ 'index_name': index}\nresponse = self.api.session.post(resource_url, files=files, data=data)\nresponse_dict = response.json()\ntimeline_dict = response_dict['objects'][0]\n" } ]
Python
Apache License 2.0
google/timesketch
fix args and linter