author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
263,133
25.05.2020 15:28:53
0
dd95094844f8272059e2b6971b1aab3c13fb0e4b
Removing unused logger.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/analyzer.py", "new_path": "api_client/python/timesketch_api_client/analyzer.py", "diff": "@@ -16,13 +16,10 @@ from __future__ import unicode_literals\nimport datetime\nimport json\n-import logging\nfrom . import definitions\nfrom . import resource\n-logger = logging.getLogger('analyzer_results')\n-\nclass AnalyzerResult(resource.BaseResource):\n\"\"\"Class to store and retrieve session information for an analyzer.\"\"\"\n" } ]
Python
Apache License 2.0
google/timesketch
Removing unused logger.
263,178
26.05.2020 08:08:27
-7,200
036a1f866265318648fd90b953e4e49dba829781
Changed setup.py to not use pip internal-only API
[ { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -25,15 +25,10 @@ import glob\nimport os\nimport sys\n+from pkg_resources import parse_requirements\nfrom setuptools import find_packages\nfrom setuptools import setup\n-try: # for pip >= 10\n- from pip._internal.download import PipSession\n- from pip._internal.req import parse_requirements\n-except ImportError: # for pip <= 9.0.3\n- from pip.download import PipSession\n- from pip.req import parse_requirements\nversion_tuple = (sys.version_info[0], sys.version_info[1])\nif version_tuple < (3, 5):\n@@ -79,9 +74,9 @@ setup(\nzip_safe=False,\nentry_points={'console_scripts': ['tsctl=timesketch.tsctl:main']},\ninstall_requires=[str(req.req) for req in parse_requirements(\n- 'requirements.txt', session=PipSession(),\n+ 'requirements.txt',\n)],\ntests_require=[str(req.req) for req in parse_requirements(\n- 'test_requirements.txt', session=PipSession(),\n+ 'test_requirements.txt',\n)],\n)\n" } ]
Python
Apache License 2.0
google/timesketch
Changed setup.py to not use pip internal-only API (#1224)
263,178
26.05.2020 10:23:59
-7,200
14e5fbc02409179f558c3928e9fb006cebadbb0e
Additional changes to setup.py to support older versions of setuptools
[ { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -25,7 +25,8 @@ import glob\nimport os\nimport sys\n-from pkg_resources import parse_requirements\n+import pkg_resources\n+\nfrom setuptools import find_packages\nfrom setuptools import setup\n@@ -38,6 +39,25 @@ if version_tuple < (3, 5):\nsys.exit(1)\n+def parse_requirements_from_file(path):\n+ \"\"\"Parses requirements from a requirements file.\n+\n+ Args:\n+ path (str): path to the requirements file.\n+\n+ Yields:\n+ pkg_resources.Requirement: package resource requirement.\n+ \"\"\"\n+ with open(path, 'r') as file_object:\n+ file_contents = file_object.read()\n+ for req in pkg_resources.parse_requirements(file_contents):\n+ try:\n+ requirement = str(req.req)\n+ except AttributeError:\n+ requirement = str(req)\n+ yield requirement\n+\n+\ntimesketch_version = '20200507'\ntimesketch_description = (\n@@ -73,10 +93,6 @@ setup(\ninclude_package_data=True,\nzip_safe=False,\nentry_points={'console_scripts': ['tsctl=timesketch.tsctl:main']},\n- install_requires=[str(req.req) for req in parse_requirements(\n- 'requirements.txt',\n- )],\n- tests_require=[str(req.req) for req in parse_requirements(\n- 'test_requirements.txt',\n- )],\n+ install_requires=parse_requirements_from_file('requirements.txt'),\n+ tests_require=parse_requirements_from_file('test_requirements.txt'),\n)\n" } ]
Python
Apache License 2.0
google/timesketch
Additional changes to setup.py to support older versions of setuptools (#1225)
263,178
26.05.2020 13:09:30
-7,200
ec1ae5e030ae313dee8aaacdfb559d9d0e4d434c
Added Ubuntu 20.04 Python 3.8 Travis CI test
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "-matrix:\n- include:\n- - name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6\"\n- env: [MODE=\"pypi\", UBUNTU_VERSION=\"18.04\"]\n+version: ~> 1.0\n+language: generic\nos: linux\n- dist: xenial\n- sudo: required\n+dist: bionic\n+jobs:\n+ include:\n+ - name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6 using PyPI\"\n+ env: [TARGET=\"pypi\", UBUNTU_VERSION=\"18.04\"]\ngroup: edge\nlanguage: python\npython: 3.6\nservices:\n- docker\n+ - name: \"Ubuntu Focal (20.04) (Docker) with Python 3.8 using PyPI\"\n+ env: [TARGET=\"pypi\", UBUNTU_VERSION=\"20.04\"]\n+ group: edge\n+ language: python\n+ python: 3.8\n+ services:\n+ - docker\ncache:\n- pip\ninstall:\n" }, { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "@@ -8,8 +8,8 @@ DPKG_PYTHON3_TEST_DEPENDENCIES=\"python3-distutils python3-flask-testing python3-\n# Exit on error.\nset -e;\n-#if test -n \"${UBUNTU_VERSION}\";\n-if test ${MODE} = \"dpkg\"; then\n+if test -n \"${UBUNTU_VERSION}\";\n+then\nCONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\ndocker pull ubuntu:${UBUNTU_VERSION};\ndocker run --name=${CONTAINER_NAME} --detach -i ubuntu:${UBUNTU_VERSION};\n@@ -34,30 +34,34 @@ if test ${MODE} = \"dpkg\"; then\n# Install packages.\nDPKG_PACKAGES=\"git\";\n- if test ${TARGET} = \"pylint\"; then\n+ if test ${TARGET} = \"pylint\";\n+ then\nDPKG_PACKAGES=\"${DPKG_PACKAGES} python3-distutils pylint\";\nfi\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} python3\";\n- DPKG_PACKAGES=\"${DPKG_PACKAGES} python3 ${DPKG_PYTHON3_DEPENDENCIES} ${DPKG_PYTHON3_TEST_DEPENDENCIES}\";\n-\n+ if test ${TARGET} = \"pypi\";\n+ then\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} python3-pip\";\n+ else\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} ${DPKG_PYTHON3_DEPENDENCIES} ${DPKG_PYTHON3_TEST_DEPENDENCIES}\";\n+ fi\ndocker exec -e \"DEBIAN_FRONTEND=noninteractive\" ${CONTAINER_NAME} sh -c \"apt-get install -y ${DPKG_PACKAGES}\";\n- docker exec cd api_client/python && python setup.py build && python setup.py install\n- docker exec cd ../../\n- docker exec cd importer_client/python && python setup.py build && python setup.py install\n- docker exec cd ../../\n+\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- cd api_client/python && python setup.py build && python setup.py install\n- cd ../../\n- cd importer_client/python && python setup.py build && python setup.py install\n+ if test ${TARGET} = \"pypi\";\n+ then\n+ docker exec ${CONTAINER_NAME} sh -c \"cd timesketch && pip3 install -r requirements.txt\";\n+ docker exec ${CONTAINER_NAME} sh -c \"cd timesketch && pip3 install -r test_requirements.txt\";\n+ docker exec ${CONTAINER_NAME} sh -c \"(cd timesketch/api_client/python && python3 setup.py build && python3 setup.py install)\";\n+ docker exec ${CONTAINER_NAME} sh -c \"(cd timesketch/importer_client/python && python3 setup.py build && python3 setup.py install)\";\n+ fi\n-elif test ${TRAVIS_OS_NAME} = \"linux\"; then\n+elif test ${TRAVIS_OS_NAME} = \"linux\";\n+then\npip3 install -r requirements.txt;\npip3 install -r test_requirements.txt;\n- cd api_client/python && python setup.py build && python setup.py install\n- cd ../../\n- cd importer_client/python && python setup.py build && python setup.py install\n+ (cd api_client/python && python setup.py build && python setup.py install);\n+ (cd importer_client/python && python setup.py build && python setup.py install);\nfi\n" }, { "change_type": "MODIFY", "old_path": "config/travis/run_python3.sh", "new_path": "config/travis/run_python3.sh", "diff": "# Exit on error.\nset -e;\n-nosetests3\n+python3 ./run_tests.py\npython3 ./setup.py build\npython3 ./setup.py sdist\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 ${MODE} = \"dpkg\"; then\n+if test -n \"${UBUNTU_VERSION}\";\n+then\nCONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\nCONTAINER_OPTIONS=\"-e LANG=en_US.UTF-8\";\n@@ -18,10 +19,8 @@ if test ${MODE} = \"dpkg\"; 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-\n-elif test \"${TRAVIS_OS_NAME}\" = \"linux\"; then\n+elif test \"${TRAVIS_OS_NAME}\" = \"linux\";\n+then\npython3 ./run_tests.py\npython3 ./setup.py bdist\n" } ]
Python
Apache License 2.0
google/timesketch
Added Ubuntu 20.04 Python 3.8 Travis CI test (#1220)
263,178
27.05.2020 10:48:43
-7,200
20a356ad52b7c522e7e627528b216a1923c4ab30
Updated dependencies and test scripts
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -4,6 +4,13 @@ os: linux\ndist: bionic\njobs:\ninclude:\n+ - name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6 using GIFT PPA\"\n+ env: UBUNTU_VERSION=\"18.04\"\n+ group: edge\n+ language: python\n+ python: 3.6\n+ services:\n+ - docker\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6 using PyPI\"\nenv: [TARGET=\"pypi\", UBUNTU_VERSION=\"18.04\"]\ngroup: edge\n@@ -18,6 +25,27 @@ jobs:\npython: 3.8\nservices:\n- docker\n+ - name: \"Ubuntu Focal (20.04) (Docker) with Python 3.6 (tox)\"\n+ env: [TOXENV=\"py36\", UBUNTU_VERSION=\"20.04\"]\n+ group: edge\n+ language: python\n+ python: 3.6\n+ services:\n+ - docker\n+ - name: \"Ubuntu Focal (20.04) (Docker) with Python 3.7 (tox)\"\n+ env: [TOXENV=\"py37\", UBUNTU_VERSION=\"20.04\"]\n+ group: edge\n+ language: python\n+ python: 3.7\n+ services:\n+ - docker\n+ - name: \"Ubuntu Focal (20.04) (Docker) with Python 3.8 (tox)\"\n+ env: [TOXENV=\"py38\", UBUNTU_VERSION=\"20.04\"]\n+ group: edge\n+ language: python\n+ python: 3.8\n+ services:\n+ - docker\ncache:\n- pip\ninstall:\n" }, { "change_type": "MODIFY", "old_path": "MANIFEST.in", "new_path": "MANIFEST.in", "diff": "include AUTHORS LICENSE README.md\n-include requirements.in requirements.txt\n+include requirements.txt test_requirements.txt\n+include run_tests.py\nexclude .gitignore\nexclude *.pyc\nrecursive-include config *\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/control", "new_path": "config/dpkg/control", "diff": "@@ -2,9 +2,9 @@ Source: timesketch\nSection: python\nPriority: extra\nMaintainer: Timesketch development team <timesketch-dev@googlegroups.com>\n-Build-Depends: debhelper (>= 9), dh-python, dh-systemd (>= 1.5), python3-all (>= 3.4~), python3-setuptools, python3-pip\n+Build-Depends: debhelper (>= 9), dh-python, dh-systemd (>= 1.5), python3-all (>= 3.6~), python3-setuptools, python3-pip\nStandards-Version: 4.1.4\n-X-Python3-Version: >= 3.5\n+X-Python3-Version: >= 3.6\nHomepage: http://timesketch.org\nPackage: timesketch-data\n@@ -18,7 +18,7 @@ Description: Data files for Timesketch\nPackage: python3-timesketch\nArchitecture: all\n-Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-markdown (>=3.1.1), python3-yaml (>= 3.10), ${python3:Depends}, ${misc:Depends}\n+Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-mans-to-es (>= 1.6), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${python3:Depends}, ${misc:Depends}\nDescription: Python 3 module of Timesketch\nTimesketch is a web based tool for collaborative forensic\ntimeline analysis. Using sketches you and your collaborators can easily\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/rules", "new_path": "config/dpkg/rules", "diff": ".PHONY: override_dh_auto_test\noverride_dh_auto_test:\n+.PHONY: override_dh_auto_install\n+override_dh_auto_install:\n+ dh_auto_install\n+ rm -f debian/tmp/usr/lib/python3*/dist-packages/timesketch-*.egg-info/requires.txt\n+\n.PHONY: override_dh_installinit\noverride_dh_installinit:\ndh_installinit --name=timesketch\n" }, { "change_type": "MODIFY", "old_path": "config/linux/gift_ppa_install.sh", "new_path": "config/linux/gift_ppa_install.sh", "diff": "@@ -8,79 +8,98 @@ set -e\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-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+PYTHON_DEPENDENCIES=\"python3-alembic\n+ python3-altair\n+ python3-amqp\n+ python3-aniso8601\n+ python3-asn1crypto\n+ python3-attr\n+ python3-bcrypt\n+ python3-billiard\n+ python3-blinker\n+ python3-bs4\n+ python3-celery\n+ python3-certifi\n+ python3-cffi\n+ python3-chardet\n+ python3-ciso8601\n+ python3-click\n+ python3-cryptography\n+ python3-datasketch\n+ python3-dateutil\n+ python3-editor\n+ python3-elasticsearch\n+ python3-entrypoints\n+ python3-flask\n+ python3-flask-bcrypt\n+ python3-flask-login\n+ python3-flask-migrate\n+ python3-flask-restful\n+ python3-flask-script\n+ python3-flask-sqlalchemy\n+ python3-flaskext.wtf\n+ python3-google-auth\n+ python3-google-auth-oauthlib\n+ python3-gunicorn\n+ python3-idna\n+ python3-itsdangerous\n+ python3-jinja2\n+ python3-jsonschema\n+ python3-jwt\n+ python3-kombu\n+ python3-mako\n+ python3-mans-to-es\n+ python3-markdown\n+ python3-markupsafe\n+ python3-neo4jrestclient\n+ python3-numpy\n+ python3-oauthlib\n+ python3-pandas\n+ python3-parameterized\n+ python3-pycparser\n+ python3-pyrsistent\n+ python3-redis\n+ python3-requests\n+ python3-requests-oauthlib\n+ python3-sigmatools\n+ python3-six\n+ python3-sqlalchemy\n+ python3-tabulate\n+ python3-toolz\n+ python3-tz\n+ python3-urllib3\n+ python3-vine\n+ python3-werkzeug\n+ python3-wtforms\n+ python3-xlrd\n+ python3-xmltodict\n+ python3-yaml\";\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- python-setuptools\";\n+TEST_DEPENDENCIES=\"python3-coverage\n+ python3-flask-testing\n+ python3-mock\n+ python3-nose\n+ python3-pbr\n+ python3-setuptools\";\n+\n+# Additional dependencies for development, alphabetized, one per line.\n+DEVELOPMENT_DEPENDENCIES=\"pylint\";\n+\n+# Additional dependencies for debugging, alphabetized, one per line.\nsudo add-apt-repository ppa:gift/dev -y\nsudo apt-get update -q\n-sudo apt-get install -y ${PYTHON2_DEPENDENCIES}\n+sudo apt-get install -y ${PYTHON_DEPENDENCIES}\n+\n+if [[ \"$*\" =~ \"include-debug\" ]]; then\n+ sudo apt-get install -y ${DEBUG_DEPENDENCIES}\n+fi\n+\n+if [[ \"$*\" =~ \"include-development\" ]]; then\n+ sudo apt-get install -y ${DEVELOPMENT_DEPENDENCIES}\n+fi\nif [[ \"$*\" =~ \"include-test\" ]]; then\nsudo apt-get install -y ${TEST_DEPENDENCIES}\n" }, { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "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+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-ciso8601 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-flaskext.wtf python3-google-auth python3-google-auth-oauthlib python3-gunicorn python3-idna python3-itsdangerous python3-jinja2 python3-jsonschema python3-jwt python3-kombu python3-mako python3-mans-to-es python3-markdown python3-markupsafe python3-neo4jrestclient python3-numpy python3-oauthlib python3-pandas python3-parameterized python3-pycparser python3-pyrsistent python3-redis python3-requests python3-requests-oauthlib python3-sigmatools python3-six python3-sqlalchemy python3-tabulate python3-toolz python3-tz python3-urllib3 python3-vine python3-werkzeug python3-wtforms python3-xlrd python3-xmltodict python3-yaml python3-zipp\";\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 python3-oauthlib python3-google-auth\";\n-DPKG_PYTHON3_TEST_DEPENDENCIES=\"python3-distutils python3-flask-testing python3-mock python3-nose python3-pip python3-pbr python3-setuptools\";\n+DPKG_PYTHON3_TEST_DEPENDENCIES=\"python3-coverage python3-distutils python3-flask-testing python3-mock python3-nose python3-pbr python3-setuptools\";\n# Exit on error.\nset -e;\n@@ -11,17 +15,24 @@ set -e;\nif test -n \"${UBUNTU_VERSION}\";\nthen\nCONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\n+\ndocker pull ubuntu:${UBUNTU_VERSION};\n+\ndocker run --name=${CONTAINER_NAME} --detach -i ubuntu:${UBUNTU_VERSION};\n# Install add-apt-repository and locale-gen.\ndocker exec ${CONTAINER_NAME} apt-get update -q;\ndocker exec -e \"DEBIAN_FRONTEND=noninteractive\" ${CONTAINER_NAME} sh -c \"apt-get install -y locales software-properties-common\";\n- docker exec ${CONTAINER_NAME} add-apt-repository universe -y;\n# Add additional apt repositories.\n- if test ${TARGET} = \"pylint\";\n+ if test -n \"${TOXENV}\";\n+ then\n+ docker exec ${CONTAINER_NAME} add-apt-repository universe;\n+ docker exec ${CONTAINER_NAME} add-apt-repository ppa:deadsnakes/ppa -y;\n+\n+ elif \"${UBUNTU_VERSION}\" = \"18.04\";\nthen\n+ # Note that run_tests.py currently requires pylint.\ndocker exec ${CONTAINER_NAME} add-apt-repository ppa:gift/pylint3 -y;\nfi\ndocker exec ${CONTAINER_NAME} add-apt-repository ppa:gift/dev -y;\n@@ -32,36 +43,48 @@ then\ndocker exec ${CONTAINER_NAME} locale-gen en_US.UTF-8;\n# Install packages.\n- DPKG_PACKAGES=\"git\";\n+ if test -n \"${TOXENV}\";\n+ then\n+ DPKG_PACKAGES=\"build-essential python${TRAVIS_PYTHON_VERSION} python${TRAVIS_PYTHON_VERSION}-dev tox\";\n+ else\n+ DPKG_PACKAGES=\"\";\n+\n+ if test \"${TARGET}\" = \"coverage\";\n+ then\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} curl git\";\n+\n+ elif test \"${TARGET}\" = \"jenkins3\";\n+ then\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} sudo\";\n- if test ${TARGET} = \"pylint\";\n+ elif test ${TARGET} = \"pylint\";\nthen\nDPKG_PACKAGES=\"${DPKG_PACKAGES} python3-distutils pylint\";\nfi\n- DPKG_PACKAGES=\"${DPKG_PACKAGES} python3\";\n-\nif test ${TARGET} = \"pypi\";\nthen\n- DPKG_PACKAGES=\"${DPKG_PACKAGES} python3-pip\";\n- else\n- DPKG_PACKAGES=\"${DPKG_PACKAGES} ${DPKG_PYTHON3_DEPENDENCIES} ${DPKG_PYTHON3_TEST_DEPENDENCIES}\";\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} python3 python3-pip\";\n+\n+ elif test \"${TARGET}\" != \"jenkins3\";\n+ then\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} python3 ${DPKG_PYTHON3_DEPENDENCIES} ${DPKG_PYTHON3_TEST_DEPENDENCIES}\";\n+\n+ # Note that run_tests.py currently requires pylint.\n+ DPKG_PACKAGES=\"${DPKG_PACKAGES} python3-distutils pylint\";\n+ fi\nfi\ndocker exec -e \"DEBIAN_FRONTEND=noninteractive\" ${CONTAINER_NAME} sh -c \"apt-get install -y ${DPKG_PACKAGES}\";\ndocker cp ../timesketch ${CONTAINER_NAME}:/\n- if test ${TARGET} = \"pypi\";\n+ if test \"${TARGET}\" = \"pypi\";\nthen\ndocker exec ${CONTAINER_NAME} sh -c \"cd timesketch && pip3 install -r requirements.txt\";\ndocker exec ${CONTAINER_NAME} sh -c \"cd timesketch && pip3 install -r test_requirements.txt\";\n- docker exec ${CONTAINER_NAME} sh -c \"(cd timesketch/api_client/python && python3 setup.py build && python3 setup.py install)\";\n- docker exec ${CONTAINER_NAME} sh -c \"(cd timesketch/importer_client/python && python3 setup.py build && python3 setup.py install)\";\n+ # The tests do not appear to require on these installs, hence they have been disabled and are kept for referrence.\n+ # docker exec ${CONTAINER_NAME} sh -c \"(cd timesketch/api_client/python && python3 setup.py build && python3 setup.py install)\";\n+ # docker exec ${CONTAINER_NAME} sh -c \"(cd timesketch/importer_client/python && python3 setup.py build && python3 setup.py install)\";\n+ else\n+ docker exec ${CONTAINER_NAME} sh -c \"ln -s /usr/bin/nosetests3 /usr/bin/nosetests\";\nfi\n-\n-elif test ${TRAVIS_OS_NAME} = \"linux\";\n-then\n- pip3 install -r requirements.txt;\n- pip3 install -r test_requirements.txt;\n- (cd api_client/python && python setup.py build && python setup.py install);\n- (cd importer_client/python && python setup.py build && python setup.py install);\nfi\n" }, { "change_type": "MODIFY", "old_path": "config/travis/run_python3.sh", "new_path": "config/travis/run_python3.sh", "diff": "#!/bin/bash\n#\n# Script to run Python 3 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# Exit on error.\nset -e;\n@@ -8,5 +11,9 @@ set -e;\npython3 ./run_tests.py\npython3 ./setup.py build\n+\npython3 ./setup.py sdist\n+\npython3 ./setup.py bdist\n+\n+python3 ./setup.py install\n" }, { "change_type": "MODIFY", "old_path": "config/travis/run_with_timeout.sh", "new_path": "config/travis/run_with_timeout.sh", "diff": "# 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# Exit on error.\nset -e\n" }, { "change_type": "MODIFY", "old_path": "config/travis/runtests.sh", "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# Exit on error.\nset -e;\n@@ -10,20 +13,36 @@ then\nCONTAINER_NAME=\"ubuntu${UBUNTU_VERSION}\";\nCONTAINER_OPTIONS=\"-e LANG=en_US.UTF-8\";\n- if test \"${TARGET}\" = \"pylint\"; then\n+ if test -n \"${TOXENV}\";\n+ then\n+ TEST_COMMAND=\"tox -e ${TOXENV}\";\n+\n+ elif test \"${TARGET}\" = \"coverage\";\n+ then\n+ # Also see: https://docs.codecov.io/docs/testing-with-docker\n+ curl -o codecov_env.sh -s https://codecov.io/env;\n+\n+ # Generates a series of -e options.\n+ CODECOV_ENV=$(/bin/bash ./codecov_env.sh);\n+\n+ CONTAINER_OPTIONS=\"${CODECOV_ENV} ${CONTAINER_OPTIONS}\";\n+\n+ TEST_COMMAND=\"./config/travis/run_coverage.sh\";\n+\n+ elif test \"${TARGET}\" = \"jenkins3\";\n+ then\n+ TEST_COMMAND=\"./config/jenkins/linux/run_end_to_end_tests_py3.sh travis\";\n+\n+ elif test \"${TARGET}\" = \"pylint\";\n+ then\nTEST_COMMAND=\"./config/travis/run_pylint.sh\";\nelse\nTEST_COMMAND=\"./config/travis/run_python3.sh\";\nfi\n-\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 \"${TRAVIS_OS_NAME}\" = \"linux\";\n+elif test \"${TARGET}\" = \"dockerfile\";\nthen\n- python3 ./run_tests.py\n-\n- python3 ./setup.py bdist\n-\n- python3 ./setup.py sdist\n+ cd config/docker && docker build --build-arg PPA_TRACK=\"dev\" -f Dockerfile .\nfi\n" }, { "change_type": "MODIFY", "old_path": "dependencies.ini", "new_path": "dependencies.ini", "diff": "@@ -70,6 +70,11 @@ dpkg_name: python3-chardet\nminimum_version: 3.0.4\nrpm_name: python3-chardet\n+[ciso8601]\n+dpkg_name: python3-ciso8601\n+minimum_version: 2.1.1\n+rpm_name: python3-ciso8601\n+\n[Click]\ndpkg_name: python3-click\nminimum_version: 6.7\n@@ -94,7 +99,6 @@ version_property: __version__\n[elasticsearch]\ndpkg_name: python3-elasticsearch\n-is_optional: true\nl2tbinaries_name: elasticsearch-py\nminimum_version: 6.0\npypi_name: elasticsearch\n@@ -149,12 +153,12 @@ rpm_name: python3-flask-wtf\n[google-auth]\ndpkg_name: python3-google-auth\nminimum_version: 1.6.3\n-rpm_name:\n+rpm_name: python3-google-auth\n[google-auth-oauthlib]\ndpkg_name: python3-google-auth-oauthlib\nminimum_version: 0.4.1\n-rpm_name:\n+rpm_name: python3-google-auth-oauthlib\n[gunicorn]\ndpkg_name: python3-gunicorn\n@@ -184,12 +188,22 @@ rpm_name: python3-jsonschema\n[kombu]\ndpkg_name: python3-kombu\nminimum_version: 4.1.0\n-rpm_name:\n+rpm_name: python3-kombu\n[Mako]\ndpkg_name: python3-mako\nminimum_version: 1.0.7\n-rpm_name:\n+rpm_name: python3-mako\n+\n+[mans-to-es]\n+dpkg_name: python3-mans-to-es\n+minimum_version: 1.6\n+rpm_name: python3-mans-to-es\n+\n+[Markdown]\n+dpkg_name: python3-markdown\n+minimum_version: 3.2.2\n+rpm_name: python3-markdown\n[MarkupSafe]\ndpkg_name: python3-markupsafe\n@@ -209,7 +223,7 @@ rpm_name: python3-numpy\n[oauthlib]\ndpkg_name: python3-oauthlib\nminimum_version: 3.1.0\n-rpm_name:\n+rpm_name: python3-oauthlib\n[pandas]\ndpkg_name: python3-pandas\n@@ -259,12 +273,12 @@ rpm_name: python3-requests\n[requests-oauthlib]\ndpkg_name: python3-requests-oauthlib\nminimum_version: 1.3.0\n-rpm_name:\n+rpm_name: python3-requests-oauthlib\n[sigmatools]\ndpkg_name: python3-sigmatools\nminimum_version: 0.15.0\n-rpm_name:\n+rpm_name: python3-sigmatools\n[six]\ndpkg_name: python3-six\n@@ -276,6 +290,11 @@ dpkg_name: python3-sqlalchemy\nminimum_version: 1.1.13\nrpm_name: python3-sqlalchemy\n+[tabulate]\n+dpkg_name: python3-tabulate\n+minimum_version: 0.8.6\n+rpm_name: python3-tabulate\n+\n[toolz]\ndpkg_name: python3-toolz\nminimum_version: 0.8.2\n@@ -304,7 +323,12 @@ rpm_name: python3-wtforms\n[xlrd]\ndpkg_name: python3-xlrd\nminimum_version: 1.2.0\n-rpm_name:\n+rpm_name: python3-xlrd\n+\n+[xmltodict]\n+dpkg_name: python3-xmltodict\n+minimum_version: 0.12.0\n+rpm_name: python3-xmltodict\n[yaml]\ndpkg_name: python3-yaml\n@@ -313,3 +337,8 @@ minimum_version: 3.10\npypi_name: PyYAML\nrpm_name: PyYAML\nversion_property: __version__\n+\n+[zipp]\n+dpkg_name: python3-zipp\n+minimum_version: 0.5\n+rpm_name: python3-zipp\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -32,9 +32,9 @@ from setuptools import setup\nversion_tuple = (sys.version_info[0], sys.version_info[1])\n-if version_tuple < (3, 5):\n+if version_tuple < (3, 6):\nprint((\n- 'Unsupported Python version: {0:s}, version 3.5 or higher '\n+ 'Unsupported Python version: {0:s}, version 3.6 or higher '\n'required.').format(sys.version))\nsys.exit(1)\n" }, { "change_type": "MODIFY", "old_path": "test_dependencies.ini", "new_path": "test_dependencies.ini", "diff": "[Flask-Testing]\n-dpkg_name: python-flask-testing\n+dpkg_name: python3-flask-testing\nminimum_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+rpm_name: python3-flask-testing\n[mock]\n-dpkg_name: python-mock\n+dpkg_name: python3-mock\nminimum_version: 2.0.0\n-rpm_name: python2-mock\n+rpm_name: python3-mock\nversion_property: __version__\n[nose]\n-dpkg_name: python-nose\n+dpkg_name: python3-nose\nminimum_version: 1.3.7\n-rpm_name: python2-nose\n+rpm_name: python3-nose\n[pbr]\n-dpkg_name: python-pbr\n+dpkg_name: python3-pbr\nminimum_version: 4.2.0\n-rpm_name: python2-pbr\n+rpm_name: python3-pbr\n[six]\n-dpkg_name: python-six\n+dpkg_name: python3-six\nminimum_version: 1.1.0\n-rpm_name: python2-six\n+rpm_name: python3-six\nversion_property: __version__\n" }, { "change_type": "MODIFY", "old_path": "test_requirements.txt", "new_path": "test_requirements.txt", "diff": "@@ -3,7 +3,6 @@ funcsigs >= 1.0.2 ; python_version < '3.0'\nmock >= 2.0.0\nnose >= 1.3.7\npbr >= 4.2.0\n-six >= 1.1.0\nbeautifulsoup4 >= 4.8.2\ncoverage >= 5.0.2\npylint >= 1.9.5 # Note: Last version to support py2\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tox.ini", "diff": "+[tox]\n+envlist = py3\n+\n+[testenv]\n+pip_pre = True\n+setenv =\n+ PYTHONPATH = {toxinidir}\n+deps =\n+ Cython\n+ -rrequirements.txt\n+ -rtest_requirements.txt\n+commands =\n+ ./run_tests.py\n+\n+[testenv:py38]\n+pip_pre = True\n+setenv =\n+ PYTHONPATH = {toxinidir}\n+deps =\n+ Cython\n+ -rrequirements.txt\n+ -rtest_requirements.txt\n+commands =\n+ coverage erase\n+ coverage run --source=timesketch --omit=\"*_test*,*__init__*,*test_lib*\" run_tests.py\n" } ]
Python
Apache License 2.0
google/timesketch
Updated dependencies and test scripts (#1222)
263,096
27.05.2020 20:31:41
-7,200
829fb28a2ebec11584f7bd4e89f156226d952691
Be a little verbose when to continue
[ { "change_type": "MODIFY", "old_path": "docker/dev/README.md", "new_path": "docker/dev/README.md", "diff": "@@ -8,6 +8,12 @@ You can run Timesketch on Docker in development mode.\ndocker-compose up -d\n```\n+If you see the folowing message you can continue\n+\n+```\n+Timesketch development server is ready!\n+```\n+\n### Find out container ID for the timesketch container\n```\n" } ]
Python
Apache License 2.0
google/timesketch
Be a little verbose when to continue (#1228)
263,178
27.05.2020 21:33:30
-7,200
ede05a2533629351542d834835692967803713f1
Added CI test for building prod Dockerfile
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -46,6 +46,9 @@ jobs:\npython: 3.8\nservices:\n- docker\n+ - name: \"Dockerfile-prod\"\n+ env: TARGET=\"dockerfile\"\n+ group: edge\ncache:\n- pip\ninstall:\n" }, { "change_type": "MODIFY", "old_path": "config/travis/runtests.sh", "new_path": "config/travis/runtests.sh", "diff": "@@ -44,5 +44,5 @@ then\nelif test \"${TARGET}\" = \"dockerfile\";\nthen\n- cd config/docker && docker build --build-arg PPA_TRACK=\"dev\" -f Dockerfile .\n+ cd docker/build && docker build --build-arg PPA_TRACK=\"dev\" -f Dockerfile-prod .\nfi\n" } ]
Python
Apache License 2.0
google/timesketch
Added CI test for building prod Dockerfile (#1232)
263,133
28.05.2020 09:33:29
0
e801ab6669f15d3bf4f40c0a953bf2e0b805e4c5
Adding the ability to create a view through the API client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200527',\n+ version='20200528',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -145,6 +145,49 @@ class Sketch(resource.BaseResource):\nreturn data_frame\n+ def create_view(self, name, query_string='', query_dsl='', query_filter=None):\n+ \"\"\"Create a view object.\n+\n+ Args:\n+ name (str): the name of the view.\n+ query_string (str): Elasticsearch query string. This is optional\n+ yet either a query string or a query DSL is required.\n+ query_dsl (str): Elasticsearch query DSL as JSON string. This is\n+ optional yet either a query string or a query DSL is required.\n+ query_filter (dict): Filter for the query as a dict.\n+\n+ Raises:\n+ RuntimeError: if neither query_string nor query_dsl is provided or\n+ if view wasn't created for some reason.\n+ \"\"\"\n+ if not (query_string or query_dsl):\n+ raise RuntimeError('You need to supply a query string or a dsl')\n+\n+ resource_url = '{0:s}/sketches/{1:d}/views/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'name': name,\n+ 'query': query_string,\n+ 'filter': query_filter,\n+ 'dsl': query_dsl,\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ if response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Unable to create view, error code: {0:d} - {1!s} '\n+ '{2!s}'.format(\n+ response.status_code, response.reason, response.text))\n+\n+ response_json = response.json()\n+ view_dict = response_json.get('objects', [{}])[0]\n+ return view_lib.View(\n+ view_id=view_dict.get('id'),\n+ view_name=name,\n+ sketch_id=self.id,\n+ api=self.api)\n+\ndef create_story(self, title):\n\"\"\"Create a story object.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to create a view through the API client.
263,178
28.05.2020 21:45:07
-7,200
1588c1c0fc5839d698eccb5a2c8d5221e60d1b59
Added CI tests for Ubuntu 20.04 with GIFT PPA
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -11,6 +11,13 @@ jobs:\npython: 3.6\nservices:\n- docker\n+ - name: \"Ubuntu Focal (20.04) (Docker) with Python 3.8 using GIFT PPA\"\n+ env: UBUNTU_VERSION=\"20.04\"\n+ group: edge\n+ language: python\n+ python: 3.8\n+ services:\n+ - docker\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6 using PyPI\"\nenv: [TARGET=\"pypi\", UBUNTU_VERSION=\"18.04\"]\ngroup: edge\n" } ]
Python
Apache License 2.0
google/timesketch
Added CI tests for Ubuntu 20.04 with GIFT PPA (#1237)
263,178
29.05.2020 09:11:25
-7,200
50558096c1a537885066d9ebf11a5e1e2524a277
Updated Linux installation script
[ { "change_type": "MODIFY", "old_path": "config/linux/gift_ppa_install.sh", "new_path": "config/linux/gift_ppa_install.sh", "diff": "# This file is generated by l2tdevtools update-dependencies.py any dependency\n# related changes should be made in dependencies.ini.\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-PYTHON_DEPENDENCIES=\"python3-alembic\n- python3-altair\n- python3-amqp\n- python3-aniso8601\n- python3-asn1crypto\n- python3-attr\n- python3-bcrypt\n- python3-billiard\n- python3-blinker\n- python3-bs4\n- python3-celery\n- python3-certifi\n- python3-cffi\n- python3-chardet\n- python3-ciso8601\n- python3-click\n- python3-cryptography\n- python3-datasketch\n- python3-dateutil\n- python3-editor\n- python3-elasticsearch\n- python3-entrypoints\n- python3-flask\n- python3-flask-bcrypt\n- python3-flask-login\n- python3-flask-migrate\n- python3-flask-restful\n- python3-flask-script\n- python3-flask-sqlalchemy\n- python3-flaskext.wtf\n- python3-google-auth\n- python3-google-auth-oauthlib\n- python3-gunicorn\n- python3-idna\n- python3-itsdangerous\n- python3-jinja2\n- python3-jsonschema\n- python3-jwt\n- python3-kombu\n- python3-mako\n- python3-mans-to-es\n- python3-markdown\n- python3-markupsafe\n- python3-neo4jrestclient\n- python3-numpy\n- python3-oauthlib\n- python3-pandas\n- python3-parameterized\n- python3-pycparser\n- python3-pyrsistent\n- python3-redis\n- python3-requests\n- python3-requests-oauthlib\n- python3-sigmatools\n- python3-six\n- python3-sqlalchemy\n- python3-tabulate\n- python3-toolz\n- python3-tz\n- python3-urllib3\n- python3-vine\n- python3-werkzeug\n- python3-wtforms\n- python3-xlrd\n- python3-xmltodict\n- python3-yaml\";\n-\n-# Additional dependencies for running tests, alphabetized, one per line.\n-TEST_DEPENDENCIES=\"python3-coverage\n- python3-flask-testing\n- python3-mock\n- python3-nose\n- python3-pbr\n- python3-setuptools\";\n-\n-# Additional dependencies for development, alphabetized, one per line.\n-DEVELOPMENT_DEPENDENCIES=\"pylint\";\n-\n-# Additional dependencies for debugging, alphabetized, one per line.\n-\n-\n-sudo add-apt-repository ppa:gift/dev -y\n-sudo apt-get update -q\n-sudo apt-get install -y ${PYTHON_DEPENDENCIES}\n-\n-if [[ \"$*\" =~ \"include-debug\" ]]; then\n- sudo apt-get install -y ${DEBUG_DEPENDENCIES}\n-fi\n-\n-if [[ \"$*\" =~ \"include-development\" ]]; then\n- sudo apt-get install -y ${DEVELOPMENT_DEPENDENCIES}\n-fi\n-\n-if [[ \"$*\" =~ \"include-test\" ]]; then\n- sudo apt-get install -y ${TEST_DEPENDENCIES}\n-fi\n+./config/linux/ubuntu_install_timesketch.sh $1\n" }, { "change_type": "ADD", "old_path": null, "new_path": "config/linux/ubuntu_install_timesketch.sh", "diff": "+#!/usr/bin/env bash\n+#\n+# Script to install timesketch on Ubuntu from the GIFT PPA.\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+PYTHON_DEPENDENCIES=\"python3-alembic\n+ python3-altair\n+ python3-amqp\n+ python3-aniso8601\n+ python3-asn1crypto\n+ python3-attr\n+ python3-bcrypt\n+ python3-billiard\n+ python3-blinker\n+ python3-bs4\n+ python3-celery\n+ python3-certifi\n+ python3-cffi\n+ python3-chardet\n+ python3-ciso8601\n+ python3-click\n+ python3-cryptography\n+ python3-datasketch\n+ python3-dateutil\n+ python3-editor\n+ python3-elasticsearch\n+ python3-entrypoints\n+ python3-flask\n+ python3-flask-bcrypt\n+ python3-flask-login\n+ python3-flask-migrate\n+ python3-flask-restful\n+ python3-flask-script\n+ python3-flask-sqlalchemy\n+ python3-flaskext.wtf\n+ python3-google-auth\n+ python3-google-auth-oauthlib\n+ python3-gunicorn\n+ python3-idna\n+ python3-itsdangerous\n+ python3-jinja2\n+ python3-jsonschema\n+ python3-jwt\n+ python3-kombu\n+ python3-mako\n+ python3-mans-to-es\n+ python3-markdown\n+ python3-markupsafe\n+ python3-neo4jrestclient\n+ python3-numpy\n+ python3-oauthlib\n+ python3-pandas\n+ python3-parameterized\n+ python3-pycparser\n+ python3-pyrsistent\n+ python3-redis\n+ python3-requests\n+ python3-requests-oauthlib\n+ python3-sigmatools\n+ python3-six\n+ python3-sqlalchemy\n+ python3-tabulate\n+ python3-toolz\n+ python3-tz\n+ python3-urllib3\n+ python3-vine\n+ python3-werkzeug\n+ python3-wtforms\n+ python3-xlrd\n+ python3-xmltodict\n+ python3-yaml\n+ python3-zipp\";\n+\n+# Additional dependencies for running tests, alphabetized, one per line.\n+TEST_DEPENDENCIES=\"python3-coverage\n+ python3-distutils\n+ python3-flask-testing\n+ python3-mock\n+ python3-nose\n+ python3-pbr\n+ python3-setuptools\";\n+\n+# Additional dependencies for development, alphabetized, one per line.\n+DEVELOPMENT_DEPENDENCIES=\"pylint\";\n+\n+# Additional dependencies for debugging, alphabetized, one per line.\n+\n+\n+sudo add-apt-repository ppa:gift/dev -y\n+sudo apt-get update -q\n+sudo apt-get install -y ${PYTHON_DEPENDENCIES}\n+\n+if [[ \"$*\" =~ \"include-debug\" ]];\n+then\n+ sudo apt-get install -y ${DEBUG_DEPENDENCIES}\n+fi\n+\n+if [[ \"$*\" =~ \"include-development\" ]];\n+then\n+ sudo apt-get install -y ${DEVELOPMENT_DEPENDENCIES}\n+fi\n+\n+if [[ \"$*\" =~ \"include-test\" ]];\n+then\n+ sudo apt-get install -y ${TEST_DEPENDENCIES}\n+fi\n" } ]
Python
Apache License 2.0
google/timesketch
Updated Linux installation script (#1241)
263,178
29.05.2020 09:14:06
-7,200
b5e9e8f75f5ebc4dbe56766f173f8e4c15f3c539
Update Dockerfile-prod to install Timesketch from GIFT PPA
[ { "change_type": "MODIFY", "old_path": "docker/build/Dockerfile-prod", "new_path": "docker/build/Dockerfile-prod", "diff": "# Use the official Docker Hub Ubuntu 18.04 base image\nFROM ubuntu:18.04\n+MAINTAINER Timesketch <timesketch-dev@googlegroups.com>\n-# Setup install environment and Timesketch dependencies\n-RUN apt-get update && apt-get -y install \\\n- apt-transport-https \\\n- apt-utils \\\n- ca-certificates \\\n- git \\\n- libffi-dev \\\n- lsb-release \\\n- software-properties-common \\\n- python3-dev \\\n- python3-pip \\\n- python3-psycopg2 \\\n- && rm -rf /var/lib/apt/lists/*\n+# Create container with:\n+# docker build --no-cache --build-arg PPA_TRACK=\"[dev|stable]\"\n+\n+ARG PPA_TRACK=stable\n+\n+ENV DEBIAN_FRONTEND=noninteractive\n+\n+RUN apt-get -y update\n+RUN apt-get -y install apt-transport-https apt-utils\n+RUN apt-get -y install libterm-readline-gnu-perl software-properties-common\n+RUN add-apt-repository -y ppa:gift/$PPA_TRACK\n+\n+RUN apt-get -y update\n+RUN apt-get -y upgrade\n+\n+# Install dependencies\n+RUN apt-get -y install ca-certificates lsb-release locales python3-psycopg2\n# Install Plaso\n-RUN add-apt-repository ppa:gift/stable\n-RUN apt-get update && apt-get -y install \\\n- plaso-tools \\\n- && rm -rf /var/lib/apt/lists/*\n+RUN apt-get -y install plaso-tools\n+\n+# Install Timesketch\n+RUN apt-get -y install timesketch-server\n+\n+# Clean up apt-get cache files\n+RUN apt-get clean && rm -rf /var/cache/apt/* /var/lib/apt/lists/*\n-# Use Python 3 pip (pip3) to install Timesketch\n-RUN pip3 install https://github.com/google/timesketch/archive/master.zip\n+# Set terminal to UTF-8 by default\n+RUN locale-gen en_US.UTF-8\n+RUN update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8\n+ENV LANG en_US.UTF-8\n+ENV LC_ALL en_US.UTF-8\n" } ]
Python
Apache License 2.0
google/timesketch
Update Dockerfile-prod to install Timesketch from GIFT PPA (#1233)
263,133
04.05.2020 16:30:26
0
1d50a062ab91b6449642f5afbdd1f4881acd54f7
Adding delete ability in API client for sketches, timelines and search indices, as well as adding checks to API
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/index.py", "new_path": "api_client/python/timesketch_api_client/index.py", "diff": "@@ -59,3 +59,11 @@ class SearchIndex(resource.BaseResource):\n\"\"\"\nsearchindex = self.lazyload_data()\nreturn searchindex['objects'][0]['index_name']\n+\n+ def delete(self):\n+ \"\"\"Deletes the index.\"\"\"\n+ resource_url = '{0:s}/searchindices/{1:d}/'.format(\n+ self.api.api_root, self.id)\n+ response = self.api.session.delete(resource_url)\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -229,6 +229,13 @@ class Sketch(resource.BaseResource):\nsketch=self,\napi=self.api)\n+ def delete(self):\n+ \"\"\"Deletes the sketch.\"\"\"\n+ resource_url = '{0:s}/sketches/{1:d}/'.format(\n+ self.api.api_root, self.id)\n+ response = self.api.session.delete(resource_url)\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\ndef add_to_acl(self, user_list=None, group_list=None, make_public=False):\n\"\"\"Add users or groups to the sketch ACL.\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/timeline.py", "new_path": "api_client/python/timesketch_api_client/timeline.py", "diff": "@@ -66,3 +66,11 @@ class Timeline(resource.BaseResource):\nindex_name = timeline['objects'][0]['searchindex']['index_name']\nself._searchindex = index_name\nreturn self._searchindex\n+\n+ def delete(self):\n+ \"\"\"Deletes the timeline.\"\"\"\n+ resource_url = '{0:s}/{1:s}'.format(\n+ self.api.api_root, self.resource_uri)\n+ response = self.api.session.delete(resource_url)\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\n" }, { "change_type": "MODIFY", "old_path": "data/timesketch.conf", "new_path": "data/timesketch.conf", "diff": "@@ -29,6 +29,12 @@ SQLALCHEMY_DATABASE_URI = 'postgresql://<USERNAME>:<PASSWORD>@localhost/timesket\nELASTIC_HOST = '127.0.0.1'\nELASTIC_PORT = 9200\n+# Define what labels should be defined that make it so that a sketch and\n+# timelines will not be deleted. This can be used to add a list of different\n+# labels that ensure that a sketch and it's associated timelines cannot be\n+# deleted.\n+LABELS_TO_PREVENT_DELETION = ['lithold']\n+\n#-------------------------------------------------------------------------------\n# Single Sign On (SSO) configuration.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -40,6 +40,7 @@ import time\nimport uuid\nimport altair as alt\n+import elasticsearch\nimport six\nfrom dateutil import parser\n@@ -179,6 +180,7 @@ class ResourceMixin(object):\n'description': fields.String,\n'status': fields.Nested(status_fields),\n'color': fields.String,\n+ 'label_string': fields.String,\n'searchindex': fields.Nested(searchindex_fields),\n'deleted': fields.Boolean,\n'created_at': fields.DateTime,\n@@ -253,6 +255,7 @@ class ResourceMixin(object):\n'aggregations': fields.Nested(aggregation_fields),\n'aggregationgroups': fields.Nested(aggregation_group_fields),\n'active_timelines': fields.List(fields.Nested(timeline_fields)),\n+ 'label_string': fields.String,\n'status': fields.Nested(status_fields),\n'created_at': fields.DateTime,\n'updated_at': fields.DateTime\n@@ -419,6 +422,9 @@ class SketchResource(ResourceMixin, Resource):\nA sketch in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\naggregators = {}\nfor _, cls in aggregator_manager.AggregatorManager.get_aggregators():\naggregators[cls.NAME] = {\n@@ -522,11 +528,22 @@ class SketchResource(ResourceMixin, Resource):\ndef delete(self, sketch_id):\n\"\"\"Handles DELETE request to the resource.\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nif not sketch.has_permission(current_user, 'delete'):\nabort(\nHTTP_STATUS_CODE_FORBIDDEN, (\n'User does not have sufficient access rights to '\n'delete a sketch.'))\n+ not_delete_labels = current_app.config.get(\n+ 'LABELS_TO_PREVENT_DELETION', [])\n+ for label in not_delete_labels:\n+ if sketch.has_label(label):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'Sketch with the label [{0:s}] cannot be deleted.'.format(\n+ label))\nsketch.set_status(status='deleted')\nreturn HTTP_STATUS_CODE_OK\n@@ -539,6 +556,9 @@ class SketchResource(ResourceMixin, Resource):\n\"\"\"\nform = NameDescriptionForm.build(request)\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nif not form.validate_on_submit():\nabort(\n@@ -643,6 +663,12 @@ class ViewListResource(ResourceMixin, Resource):\nViews in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\nreturn self.to_json(sketch.get_named_views)\n@login_required\n@@ -661,6 +687,12 @@ class ViewListResource(ResourceMixin, Resource):\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to save view, not able to validate form data.')\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\nview = self.create_view_from_form(sketch, form)\nreturn self.to_json(view, status_code=HTTP_STATUS_CODE_CREATED)\n@@ -680,8 +712,15 @@ class ViewResource(ResourceMixin, Resource):\nA view in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nview = View.query.get(view_id)\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\n# Check that this view belongs to the sketch\nif view.sketch_id != sketch.id:\nabort(\n@@ -720,7 +759,16 @@ class ViewResource(ResourceMixin, Resource):\nview_id: Integer primary key for a view database model\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'delete'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have delete access controls on sketch.')\nview = View.query.get(view_id)\n+ if not view:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No view found with this ID.')\n# Check that this view belongs to the sketch\nif view.sketch_id != sketch.id:\n@@ -754,6 +802,12 @@ class ViewResource(ResourceMixin, Resource):\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to update view, not able to validate form data')\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\nview = View.query.get(view_id)\nview.query_string = form.query.data\nview.query_filter = json.dumps(form.filter.data, ensure_ascii=False)\n@@ -816,6 +870,14 @@ class ExploreResource(ResourceMixin, Resource):\nJSON with list of matched events\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\nform = ExploreForm.build(request)\nif not form.validate_on_submit():\n@@ -964,6 +1026,12 @@ class AggregationResource(ResourceMixin, Resource):\nJSON with aggregation results\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\naggregation = Aggregation.query.get(aggregation_id)\n# Check that this aggregation belongs to the sketch\n@@ -1007,6 +1075,9 @@ class AggregationResource(ResourceMixin, Resource):\nif not sketch:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\naggregation = Aggregation.query.get(aggregation_id)\nif not aggregation:\n@@ -1340,6 +1411,13 @@ class AggregationExploreResource(ResourceMixin, Resource):\n'Not able to run aggregation, unable to validate form data.')\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\nsketch_indices = {\nt.searchindex.index_name\nfor t in sketch.timelines\n@@ -1431,6 +1509,13 @@ class AggregationListResource(ResourceMixin, Resource):\nViews in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\naggregations = sketch.get_named_aggregations\nreturn self.to_json(aggregations)\n@@ -1526,6 +1611,10 @@ class AggregationGroupListResource(ResourceMixin, Resource):\nViews in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\nif not sketch.has_permission(user=current_user, permission='read'):\nabort(\nHTTP_STATUS_CODE_FORBIDDEN,\n@@ -1561,6 +1650,10 @@ class AggregationGroupListResource(ResourceMixin, Resource):\nAn aggregation in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\nif not sketch.has_permission(user=current_user, permission='write'):\nabort(\nHTTP_STATUS_CODE_FORBIDDEN,\n@@ -1621,6 +1714,13 @@ class AggregationLegacyResource(ResourceMixin, Resource):\nJSON with aggregation results\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\nform = AggregationLegacyForm.build(request)\nif not form.validate_on_submit():\n@@ -1698,6 +1798,13 @@ class EventCreateResource(ResourceMixin, Resource):\n'Failed to add event, form data not validated')\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\n+\ntimeline_name = 'sketch specific timeline'\nindex_name_seed = 'timesketch' + str(sketch_id)\nevent_type = 'user_created_event'\n@@ -1810,6 +1917,13 @@ class EventResource(ResourceMixin, Resource):\nargs = self.parser.parse_args()\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\nsearchindex_id = args.get('searchindex_id')\nsearchindex = SearchIndex.query.filter_by(\nindex_name=searchindex_id).first()\n@@ -1969,6 +2083,13 @@ class EventAnnotationResource(ResourceMixin, Resource):\nannotations = []\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\n+\nindices = [t.searchindex.index_name for t in sketch.timelines]\nannotation_type = form.annotation_type.data\nevents = form.events.raw_data\n@@ -2271,6 +2392,11 @@ class UploadFileResource(ResourceMixin, Resource):\nsketch = None\nif sketch_id:\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No sketch found with this ID.')\n+\nindex_name = form.get('index_name', uuid.uuid4().hex)\nif not isinstance(index_name, six.text_type):\n@@ -2346,6 +2472,13 @@ class StoryListResource(ResourceMixin, Resource):\nStories in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\nstories = []\nfor story in Story.query.filter_by(\nsketch=sketch).order_by(desc(Story.created_at)):\n@@ -2367,10 +2500,17 @@ class StoryListResource(ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate form data.')\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\n+\ntitle = ''\nif form.title.data:\ntitle = form.title.data\n- sketch = Sketch.query.get_with_acl(sketch_id)\nstory = Story(\ntitle=title, content='[]', sketch=sketch, user=current_user)\ndb_session.add(story)\n@@ -2435,6 +2575,10 @@ class StoryResource(ResourceMixin, Resource):\nmsg = 'No sketch found with this ID.'\nabort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\n# Check that this story belongs to the sketch\nif story.sketch_id != sketch.id:\nabort(\n@@ -2479,6 +2623,10 @@ class StoryResource(ResourceMixin, Resource):\n'Sketch ID ({0:d}) does not match with the ID in '\n'the story ({1:d})'.format(sketch.id, story.sketch_id))\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\n+\nform = request.json\nif not form:\nform = request.data\n@@ -2548,6 +2696,12 @@ class QueryResource(ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate form data.')\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\nschema = {\n'objects': [],\n'meta': {}}\n@@ -2574,6 +2728,12 @@ class CountEventsResource(ResourceMixin, Resource):\nNumber of events in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\nindices = [t.searchindex.index_name for t in sketch.active_timelines]\ncount = self.datastore.count(indices)\nmeta = dict(count=count)\n@@ -2609,6 +2769,10 @@ class TimelineCreateResource(ResourceMixin, Resource):\nsketch = None\nif sketch_id:\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No sketch found with this ID.')\n# We do not need a human readable filename or\n# datastore index name, so we use UUIDs here.\n@@ -2663,6 +2827,9 @@ class AnalysisResource(ResourceMixin, Resource):\nAn analysis in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nif not sketch:\nabort(\n@@ -2695,6 +2862,10 @@ class AnalyzerSessionResource(ResourceMixin, Resource):\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\nif not sketch.has_permission(current_user, 'read'):\nabort(\nHTTP_STATUS_CODE_FORBIDDEN,\n@@ -2716,6 +2887,9 @@ class AnalyzerRunResource(ResourceMixin, Resource):\nA list of all available analyzer names.\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nif not sketch.has_permission(current_user, 'read'):\nabort(\nHTTP_STATUS_CODE_FORBIDDEN,\n@@ -2733,6 +2907,9 @@ 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:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nif not sketch.has_permission(current_user, 'read'):\nreturn abort(\nHTTP_STATUS_CODE_FORBIDDEN,\n@@ -2819,6 +2996,12 @@ class TimelineListResource(ResourceMixin, Resource):\nView in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\nreturn self.to_json(sketch.timelines)\n@login_required\n@@ -2829,6 +3012,13 @@ class TimelineListResource(ResourceMixin, Resource):\nA sketch in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\nform = AddTimelineSimpleForm.build(request)\nmetadata = {'created': True}\n@@ -2893,6 +3083,9 @@ class TimelineResource(ResourceMixin, Resource):\ntimeline_id: Integer primary key for a timeline database model\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\ntimeline = Timeline.query.get(timeline_id)\n# Check that this timeline belongs to the sketch\n@@ -2918,6 +3111,9 @@ class TimelineResource(ResourceMixin, Resource):\ntimeline_id: Integer primary key for a timeline database model\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\ntimeline = Timeline.query.get(timeline_id)\nform = TimelineForm.build(request)\n@@ -2954,6 +3150,9 @@ class TimelineResource(ResourceMixin, Resource):\ntimeline_id: Integer primary key for a timeline database model\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\ntimeline = Timeline.query.get(timeline_id)\n# Check that this timeline belongs to the sketch\n@@ -2973,6 +3172,15 @@ class TimelineResource(ResourceMixin, Resource):\nHTTP_STATUS_CODE_FORBIDDEN,\n'The user does not have write permission on the sketch.')\n+ not_delete_labels = current_app.config.get(\n+ 'LABELS_TO_PREVENT_DELETION', [])\n+ for label in not_delete_labels:\n+ if timeline.has_label(label):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'Timelines with label [{0:s}] cannot be deleted.'.format(\n+ label))\n+\nsketch.timelines.remove(timeline)\ndb_session.commit()\nreturn HTTP_STATUS_CODE_OK\n@@ -3158,6 +3366,36 @@ class SearchIndexResource(ResourceMixin, Resource):\nsearchindex = SearchIndex.query.get_with_acl(searchindex_id)\nreturn self.to_json(searchindex)\n+ @login_required\n+ def delete(self, searchindex_id):\n+ \"\"\"Handles DELETE request to the resource.\"\"\"\n+ searchindex = SearchIndex.query.get_with_acl(searchindex_id)\n+ if not searchindex:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No searchindex found with this ID.')\n+\n+ timelines = Timeline.query.filter_by(searchindex=searchindex).all()\n+ sketches = [\n+ t.sketch for t in timelines\n+ if t.sketch and t.sketch.get_status.status != 'deleted'\n+ ]\n+ if sketches:\n+ error_strings = ['WARNING: This timeline is in use by:']\n+ for sketch in sketches:\n+ error_strings.append(' * {0:s}'.format(sketch.name))\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ '\\n'.join(error_strings))\n+\n+ db_session.delete(searchindex)\n+ db_session.commit()\n+ try:\n+ es.client.indices.delete(index=searchindex.index_name)\n+ except elasticsearch.NotFoundError:\n+ pass\n+ return HTTP_STATUS_CODE_OK\n+\nclass UserListResource(ResourceMixin, Resource):\n\"\"\"Resource to get list of users.\"\"\"\n@@ -3196,6 +3434,9 @@ class CollaboratorResource(ResourceMixin, Resource):\nsketch_id: Integer primary key for a sketch database model\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\nform = request.json\n# TODO: Add granular ACL controls.\n@@ -3264,8 +3505,15 @@ class SessionResource(ResourceMixin, Resource):\nsessions = []\nisTruncated = False\n- #check the timeline belongs to the sketch\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\n+ #check the timeline belongs to the sketch\nsketch_indices = {t.searchindex.index_name for t in sketch.timelines\nif t.searchindex.index_name == timeline_index}\n" } ]
Python
Apache License 2.0
google/timesketch
Adding delete ability in API client for sketches, timelines and search indices, as well as adding checks to API
263,133
05.05.2020 10:16:51
0
002b4b9fdeb9e434e815677dc648cd89c55becdc
Adding the archieve API call, not implemented yet.
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -411,6 +411,24 @@ class SketchListResource(ResourceMixin, Resource):\nreturn self.to_json(sketch, status_code=HTTP_STATUS_CODE_CREATED)\n+class SketchArchiveResource(ResourceMixin, Resource):\n+ \"\"\"Resource to archive a sketch.\"\"\"\n+\n+ @login_required\n+ def get(self, sketch_id):\n+ \"\"\"Handles GET request to the resource.\n+\n+ Returns:\n+ A sketch in JSON (instance of flask.wrappers.Response)\n+ \"\"\"\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ # TODO: Implement what is missing.\n+\n+\nclass SketchResource(ResourceMixin, Resource):\n\"\"\"Resource to get a sketch.\"\"\"\n@@ -425,6 +443,7 @@ class SketchResource(ResourceMixin, Resource):\nif not sketch:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\naggregators = {}\nfor _, cls in aggregator_manager.AggregatorManager.get_aggregators():\naggregators[cls.NAME] = {\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/routes.py", "new_path": "timesketch/api/v1/routes.py", "diff": "@@ -34,6 +34,7 @@ from .resources import GraphResource\nfrom .resources import GraphViewListResource\nfrom .resources import GraphViewResource\nfrom .resources import SketchResource\n+from .resources import SketchArchiveResource\nfrom .resources import SketchListResource\nfrom .resources import ViewResource\nfrom .resources import ViewListResource\n@@ -62,6 +63,7 @@ from .resources import LoggedInUserResource\nAPI_ROUTES = [\n(SketchListResource, '/sketches/'),\n(SketchResource, '/sketches/<int:sketch_id>/'),\n+ (SketchArchiveResource, '/sketches/<int:sketch_id>/archive'),\n(AnalysisResource, '/sketches/<int:sketch_id>/timelines/<int:timeline_id>/analysis/'),\n(AnalyzerRunResource, '/sketches/<int:sketch_id>/analyzer/'),\n(AnalyzerSessionResource, '/sketches/<int:sketch_id>/analyzer/sessions/<int:session_id>/'),\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the archieve API call, not implemented yet.
263,133
02.06.2020 11:39:16
0
41854dd0c9511692e2684635d2b77d3bb8937894
Forgot to include helper test last time.
[ { "change_type": "ADD", "old_path": null, "new_path": "importer_client/python/timesketch_import_client/helper_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+import tempfile\n+\n+import pandas\n+\n+from . import helper\n+\n+\n+MOCK_CONFIG = \"\"\"\n+foobar:\n+ message: 'The {cA} went bananas with {cC}, but without letting {cD} know.'\n+ timestamp_desc: 'Event Logged'\n+ datetime: 'cB'\n+ columns_subset: 'cA,cB,cC,cD'\n+\n+bar:\n+ message: 'Some people {stuff}, with {other}'\n+ timestamp_desc: 'Stuff Happened'\n+ separator: '>'\n+ encoding: 'secret-formula'\n+ data_type: 'data:secret:message'\n+\n+vindur:\n+ message: 'Vedrid i dag er: {vedur}, med typiskri {auka}'\n+ timestamp_desc: 'Thu Veist Thad'\n+ columns: 'vedur,magn,auka,rigning'\n+\"\"\"\n+\n+class MockStreamer:\n+ \"\"\"Mock streamer object for testing.\"\"\"\n+\n+ def __init__(self):\n+ \"\"\"Initialize.\"\"\"\n+ self.format_string = ''\n+ self.timestamp_description = ''\n+ self.csv_delimiter = ''\n+ self.text_encoding = ''\n+ self.datetime_column = ''\n+\n+ def set_message_format_string(self, message):\n+ self.format_string = message\n+\n+ def set_timestamp_description(self, timestamp_desc):\n+ self.timestamp_description = timestamp_desc\n+\n+ def set_csv_delimiter(self, separator):\n+ self.csv_delimiter = separator\n+\n+ def set_text_encoding(self, encoding):\n+ self.text_encoding = encoding\n+\n+ def set_datetime_column(self, datetime_string):\n+ self.datetime_column = datetime_string\n+\n+\n+class TimesketchHelperTest(unittest.TestCase):\n+ \"\"\"Test Timesketch import helper.\"\"\"\n+\n+ def setUp(self):\n+ \"\"\"Set up the test.\"\"\"\n+ self._helper = helper.ImportHelper()\n+ with tempfile.NamedTemporaryFile('w', suffix='.yaml') as fw:\n+ fw.write(MOCK_CONFIG)\n+ fw.seek(0)\n+ self._helper.add_config(fw.name)\n+\n+ def test_not_config(self):\n+ \"\"\"Test a helper that does not match.\"\"\"\n+ streamer = MockStreamer()\n+ self._helper.configure_streamer(streamer, data_type='foo:no')\n+\n+ self.assertEqual(streamer.format_string, '')\n+ self.assertEqual(streamer.timestamp_description, '')\n+ self.assertEqual(streamer.csv_delimiter, '')\n+ self.assertEqual(streamer.text_encoding, '')\n+ self.assertEqual(streamer.datetime_column, '')\n+\n+ def test_sub_column(self):\n+ \"\"\"Test a helper that matches on sub columns.\"\"\"\n+ streamer = MockStreamer()\n+ self._helper.configure_streamer(\n+ streamer, data_type='foo:no',\n+ columns=['cA', 'cB', 'cC', 'cD', 'cE', 'cF', 'cG'])\n+\n+ self.assertEqual(\n+ streamer.format_string,\n+ 'The {cA} went bananas with {cC}, but without letting {cD} know.')\n+ self.assertEqual(streamer.timestamp_description, 'Event Logged')\n+ self.assertEqual(streamer.csv_delimiter, '')\n+ self.assertEqual(streamer.text_encoding, '')\n+ self.assertEqual(streamer.datetime_column, 'cB')\n+\n+ def test_columns(self):\n+ \"\"\"Test a helper that matches on columns.\"\"\"\n+ streamer = MockStreamer()\n+ self._helper.configure_streamer(\n+ streamer, data_type='foo:no',\n+ columns=['vedur', 'magn', 'auka' ,'rigning'])\n+\n+ self.assertEqual(\n+ streamer.format_string,\n+ 'Vedrid i dag er: {vedur}, med typiskri {auka}')\n+ self.assertEqual(streamer.timestamp_description, 'Thu Veist Thad')\n+ self.assertEqual(streamer.csv_delimiter, '')\n+ self.assertEqual(streamer.text_encoding, '')\n+ self.assertEqual(streamer.datetime_column, '')\n+\n+ def test_data_type(self):\n+ \"\"\"Test a helper that matches on data_type.\"\"\"\n+ streamer = MockStreamer()\n+ self._helper.configure_streamer(\n+ streamer, data_type='data:secret:message',\n+ columns=['vedur', 'auka' ,'rigning'])\n+\n+ self.assertEqual(\n+ streamer.format_string,\n+ 'Some people {stuff}, with {other}')\n+ self.assertEqual(streamer.timestamp_description, 'Stuff Happened')\n+ self.assertEqual(streamer.csv_delimiter, '>')\n+ self.assertEqual(streamer.text_encoding, 'secret-formula')\n+ self.assertEqual(streamer.datetime_column, '')\n" } ]
Python
Apache License 2.0
google/timesketch
Forgot to include helper test last time.
263,133
02.06.2020 13:02:56
0
4091ed05db43afe181486527dc27cdbf9fb3337d
Adding ability to archive/unarchive in export
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -112,7 +112,6 @@ from timesketch.models.user import Group\nlogger = logging.getLogger('api_resources')\nARCHIVE_LABEL = 'archived'\n-logger = logging.getLogger('api_resources')\ndef bad_request(message):\n@@ -538,6 +537,10 @@ class SketchArchiveResource(ResourceMixin, Resource):\ndef _export_sketch(self, sketch):\n\"\"\"Returns a ZIP file with the exported content of a sketch.\"\"\"\nfile_object = io.BytesIO()\n+ is_archived = story.has_label(ARCHIVE_LABEL)\n+\n+ if is_archived:\n+ _ = self._unarchive_sketch(sketch)\nstory_exporter = story_export_manager.StoryExportManager.get_exporter(\n'html')\n@@ -673,6 +676,9 @@ class SketchArchiveResource(ResourceMixin, Resource):\n# TODO (kiddi): Add in support for all tagged events (includes\n# a metadata file with a list of all tags and their count).\n+ if is_archived:\n+ _ = self._archive_sketch(sketch)\n+\nfile_object.seek(0)\nreturn send_file(\nfile_object, mimetype='zip',\n" } ]
Python
Apache License 2.0
google/timesketch
Adding ability to archive/unarchive in export
263,133
02.06.2020 15:58:52
0
f7c9f6f076e183fee39706bca535f5d6034a99e1
Adding an export story to the API client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -1141,3 +1141,39 @@ class Sketch(resource.BaseResource):\nreturn_status = response.status_code in definitions.HTTP_STATUS_CODE_20X\nself._archived = return_status\nreturn return_status\n+\n+ def export(self, file_path):\n+ \"\"\"Exports the content of the story to a ZIP file.\n+\n+ Args:\n+ file_path (str): a file path where the ZIP file will be saved.\n+\n+ Raises:\n+ RuntimeError: if sketch cannot be exported.\n+ \"\"\"\n+ directory = os.path.dirname(file_path)\n+ if not os.path.isdir(directory):\n+ raise RuntimeError(\n+ 'The directory needs to exist, please create: '\n+ '%s first', directory)\n+\n+ if not file_path.lower().endswith('.zip'):\n+ raise RuntimeError('File needs to have a .zip extension.')\n+\n+ if os.path.isfile(file_path):\n+ raise RuntimeError('File [%s] already exists.', file_path)\n+\n+ form_data = {\n+ 'action': 'export'\n+ }\n+ resource_url = '{0:s}/sketches/{1:d}/archive/'.format(\n+ self.api.api_root, self.id)\n+\n+ response = self.api.session.post(resource_url, json=form_data)\n+ if response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n+ error.error_message(\n+ response, message='Failed exporting the sketch',\n+ error=RuntimeError)\n+\n+ with open(file_path, 'wb') as fw:\n+ fw.write(response.content)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding an export story to the API client.
263,096
03.06.2020 16:23:47
-7,200
42dc2013e91f294d558b95ccdf8370f33c81b496
Fix Docker Readme link (fixes During the Docker readme was moved to docker/e2e/ And while we do not have a general docker readme, it is better to link to the docker dir than 404. This was brought up in Should be a quick review
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -20,7 +20,7 @@ Timesketch is an open source tool for collaborative forensic timeline analysis.\n#### Installation\n* [Install Timesketch manually](docs/Installation.md)\n-* [Use Docker](docker/README.md)\n+* [Use Docker](docker/)\n* [Upgrade from existing installation](docs/Upgrading.md)\n#### Adding timelines\n" } ]
Python
Apache License 2.0
google/timesketch
Fix Docker Readme link (fixes #1247) During https://github.com/google/timesketch/pull/1207/files the Docker readme was moved to docker/e2e/ And while we do not have a general docker readme, it is better to link to the docker dir than 404. This was brought up in https://github.com/google/timesketch/issues/1247 Should be a quick review
263,133
05.06.2020 11:01:36
0
dd86d1cd5fe50e7a134463a96f2fded4bad88d13
Hot patching
[ { "change_type": "MODIFY", "old_path": "timesketch/__init__.py", "new_path": "timesketch/__init__.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n+\n+\n+# TODO: Remove once a new plaso release comes out.\n+def create_app(config=None):\n+ \"\"\"Create the Flask app instance that is used throughout the application.\n+\n+ Args:\n+ config: Path to configuration file as a string or an object with config\n+ directives.\n+\n+ Returns:\n+ Application object (instance of flask.Flask).\n+ \"\"\"\n+ # pylint: disable=import-outside-toplevel\n+ from timesketch import app\n+ return app.create_app(config)\n" } ]
Python
Apache License 2.0
google/timesketch
Hot patching (#1255)
263,133
05.06.2020 14:15:39
0
d757ec10776eeb2c356fbf3467bb856308b81f20
Fixing an issue in the event tagging API call.
[ { "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='20200603',\n+ version='20200605',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -1105,7 +1105,7 @@ class Sketch(resource.BaseResource):\nRuntimeError: if the sketch is archived.\nReturns:\n- Dictionary with query results.\n+ A boolean indicating whether the operation was successful or not.\n\"\"\"\nif self.is_archived():\nraise RuntimeError(\n@@ -1124,7 +1124,7 @@ class Sketch(resource.BaseResource):\nresource_url = '{0:s}/sketches/{1:d}/event/tagging/'.format(\nself.api.api_root, self.id)\nresponse = self.api.session.post(resource_url, json=form_data)\n- return response.json()\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\ndef search_by_label(self, label_name, as_pandas=False):\n\"\"\"Searches for all events containing a given label.\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing an issue in the event tagging API call.
263,133
08.06.2020 07:16:09
0
26b1574802f5ef82e5bcff69605964a36b30f92f
Adding labels.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/index.py", "new_path": "api_client/python/timesketch_api_client/index.py", "diff": "@@ -39,11 +39,32 @@ class SearchIndex(resource.BaseResource):\nsearchindex_name: Name of the searchindex (optional).\n\"\"\"\nself.id = searchindex_id\n+ self._labels = []\nself._searchindex_name = searchindex_name\nself._resource_uri = 'searchindices/{0:d}'.format(self.id)\nsuper(SearchIndex, self).__init__(\napi=api, resource_uri=self._resource_uri)\n+ @property\n+ def labels(self):\n+ \"\"\"Property that returns the SearchIndex labels.\"\"\"\n+ if self._labels:\n+ return self._labels\n+\n+ data = self.lazyload_data()\n+ objects = data.get('objects', [])\n+ if not objects:\n+ return self._labels\n+\n+ index_data = objects[0]\n+ label_string = index_data.get('label_string', '')\n+ if label_string:\n+ self._labels = json.loads(label_string)\n+ else:\n+ self._labels = []\n+\n+ return self._labels\n+\n@property\ndef name(self):\n\"\"\"Property that returns searchindex name.\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": "@@ -58,10 +58,31 @@ class Sketch(resource.BaseResource):\nself.id = sketch_id\nself.api = api\nself._archived = None\n+ self._labels = []\nself._sketch_name = sketch_name\nself._resource_uri = 'sketches/{0:d}'.format(self.id)\nsuper(Sketch, self).__init__(api=api, resource_uri=self._resource_uri)\n+ @property\n+ def labels(self):\n+ \"\"\"Property that returns the sketch labels.\"\"\"\n+ if self._labels:\n+ return self._labels\n+\n+ data = self.lazyload_data()\n+ objects = data.get('objects', [])\n+ if not objects:\n+ return self._labels\n+\n+ sketch_data = objects[0]\n+ label_string = sketch_data.get('label_string', '')\n+ if label_string:\n+ self._labels = json.loads(label_string)\n+ else:\n+ self._labels = []\n+\n+ return self._labels\n+\n@property\ndef name(self):\n\"\"\"Property that returns sketch name.\n@@ -1229,7 +1250,10 @@ class Sketch(resource.BaseResource):\n}\nresponse = self.api.session.post(resource_url, json=data)\nreturn_status = error.check_return_status(response, logger)\n- self._archived = return_status\n+\n+ # return_status = True means unarchive is successful or that\n+ # the archive status is False.\n+ self._archived = not return_status\nreturn return_status\ndef export(self, file_path):\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/timeline.py", "new_path": "api_client/python/timesketch_api_client/timeline.py", "diff": "@@ -42,12 +42,33 @@ class Timeline(resource.BaseResource):\nsearchindex: The Elasticsearch index name (optional)\n\"\"\"\nself.id = timeline_id\n+ self._labels = []\nself._name = name\nself._searchindex = searchindex\nresource_uri = 'sketches/{0:d}/timelines/{1:d}/'.format(\nsketch_id, self.id)\nsuper(Timeline, self).__init__(api, resource_uri)\n+ @property\n+ def labels(self):\n+ \"\"\"Property that returns the timeline labels.\"\"\"\n+ if self._labels:\n+ return self._labels\n+\n+ data = self.lazyload_data()\n+ objects = data.get('objects', [])\n+ if not objects:\n+ return self._labels\n+\n+ timeline_data = objects[0]\n+ label_string = timeline_data.get('label_string', '')\n+ if label_string:\n+ self._labels = json.loads(label_string)\n+ else:\n+ self._labels = []\n+\n+ return self._labels\n+\n@property\ndef name(self):\n\"\"\"Property that returns timeline name.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding labels.
263,133
08.06.2020 07:40:59
0
60f510e58d0b397567bb2f112a6cc5997adfeadf
Changing the necessary permissions to call archive/export on sketches.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/index.py", "new_path": "api_client/python/timesketch_api_client/index.py", "diff": "\"\"\"Timesketch API client library.\"\"\"\nfrom __future__ import unicode_literals\n+import json\nimport logging\nfrom . import error\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/timeline.py", "new_path": "api_client/python/timesketch_api_client/timeline.py", "diff": "\"\"\"Timesketch API client library.\"\"\"\nfrom __future__ import unicode_literals\n+import json\nimport logging\nfrom . import error\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/archive.py", "new_path": "timesketch/api/v1/archive.py", "diff": "@@ -245,12 +245,6 @@ class SketchArchiveResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n- if not sketch.has_permission(current_user, 'delete'):\n- abort(\n- HTTP_STATUS_CODE_FORBIDDEN, (\n- 'User does not have sufficient access rights to '\n- 'delete a sketch.'))\n-\nself._sketch = sketch\nform = request.json\nif not form:\n@@ -258,12 +252,30 @@ class SketchArchiveResource(resources.ResourceMixin, Resource):\naction = form.get('action', '')\nif action == 'archive':\n+ if not sketch.has_permission(current_user, 'delete'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have sufficient access rights to '\n+ 'delete a sketch.')\n+\nreturn self._archive_sketch(sketch)\nif action == 'export':\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN, (\n+ 'User does not have sufficient access rights to '\n+ 'read a sketch.'))\n+\nreturn self._export_sketch(sketch)\nif action == 'unarchive':\n+ if not sketch.has_permission(current_user, 'delete'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN, (\n+ 'User does not have sufficient access rights to '\n+ 'delete a sketch.'))\n+\nreturn self._unarchive_sketch(sketch)\nreturn abort(\n" } ]
Python
Apache License 2.0
google/timesketch
Changing the necessary permissions to call archive/export on sketches.
263,178
09.06.2020 08:12:46
-7,200
93ee9a3cc288466cd4fc9bf56f0c8cbd16040d4f
Pinned pylint to version 2.4.x and addressed linter issues
[ { "change_type": "MODIFY", "old_path": "test_requirements.txt", "new_path": "test_requirements.txt", "diff": "Flask-Testing >= 0.6.2\n-funcsigs >= 1.0.2 ; python_version < '3.0'\nmock >= 2.0.0\nnose >= 1.3.7\npbr >= 4.2.0\nbeautifulsoup4 >= 4.8.2\ncoverage >= 5.0.2\n-pylint >= 1.9.5 # Note: Last version to support py2\n+pylint >= 2.4.0, < 2.5.0\n" }, { "change_type": "MODIFY", "old_path": "timesketch/__init__.py", "new_path": "timesketch/__init__.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n+\"\"\"Entry point for the application.\"\"\"\n# TODO: Remove once a new plaso release comes out.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/archive.py", "new_path": "timesketch/api/v1/resources/archive.py", "diff": "@@ -21,8 +21,6 @@ import json\nimport logging\nimport zipfile\n-import pandas as pd\n-\nfrom flask import abort\nfrom flask import current_app\nfrom flask import jsonify\n@@ -32,6 +30,8 @@ from flask_login import current_user\nfrom flask_login import login_required\nfrom flask_restful import Resource\n+import pandas as pd\n+\nfrom timesketch import version\nfrom timesketch.api.v1 import resources\nfrom timesketch.api.v1 import utils\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/utils.py", "new_path": "timesketch/api/v1/utils.py", "diff": "@@ -18,10 +18,11 @@ from __future__ import unicode_literals\nimport json\nimport time\n-import altair as alt\nfrom flask import abort\nfrom flask import jsonify\n+import altair as alt\n+\nfrom timesketch.lib.aggregators import manager as aggregator_manager\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\n" }, { "change_type": "MODIFY", "old_path": "timesketch/app.py", "new_path": "timesketch/app.py", "diff": "@@ -20,8 +20,9 @@ import sys\nimport six\n-from celery import Celery\nfrom flask import Flask\n+from celery import Celery\n+\nfrom flask_login import LoginManager\nfrom flask_migrate import Migrate\nfrom flask_restful import Api\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -23,9 +23,10 @@ import time\nimport traceback\nimport yaml\n+from flask import current_app\n+\nimport pandas\n-from flask import current_app\nfrom timesketch.lib import definitions\nfrom timesketch.lib.datastores.elastic import ElasticsearchDataStore\nfrom timesketch.models import db_session\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/manager_test.py", "new_path": "timesketch/lib/analyzers/manager_test.py", "diff": "@@ -73,8 +73,8 @@ class TestAnalysisManager(BaseTest):\ndef test_get_analyzers(self):\n\"\"\"Test to get analyzer class objects.\"\"\"\nanalyzers = manager.AnalysisManager.get_analyzers()\n- analyzer_list = [x for x in analyzers]\n- self.assertIsInstance(analyzer_list, list)\n+ analyzer_list = list(analyzers)\n+\nanalyzer_dict = {}\nfor name, analyzer_class in analyzer_list:\nanalyzer_dict[name] = analyzer_class\n@@ -84,7 +84,7 @@ class TestAnalysisManager(BaseTest):\nmanager.AnalysisManager.clear_registration()\nanalyzers = manager.AnalysisManager.get_analyzers()\n- analyzer_list = [x for x in analyzers]\n+ analyzer_list = list(analyzers)\nself.assertEqual(analyzer_list, [])\nmanager.AnalysisManager.register_analyzer(MockAnalyzer)\n@@ -93,9 +93,9 @@ class TestAnalysisManager(BaseTest):\nmanager.AnalysisManager.register_analyzer(MockAnalyzer4)\nanalyzers = manager.AnalysisManager.get_analyzers()\n- analyzer_list = [x for x, _ in analyzers]\n- self.assertEqual(len(analyzer_list), 4)\n- self.assertIn('mockanalyzer', analyzer_list)\n+ analyzer_names_list = [x for x, _ in analyzers]\n+ self.assertEqual(len(analyzer_names_list), 4)\n+ self.assertIn('mockanalyzer', analyzer_names_list)\n# pylint: disable=protected-access\nanalyzers_to_run = [\n@@ -117,7 +117,7 @@ class TestAnalysisManager(BaseTest):\nmanager.AnalysisManager.register_analyzer(MockAnalyzerFail2)\nwith self.assertRaises(KeyError):\nanalyzers = manager.AnalysisManager.get_analyzers()\n- analyzer_list = [x for x, _ in analyzers]\n+ _ = list(analyzers)\ndef test_get_analyzer(self):\n\"\"\"Test to get analyzer class from registry.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/phishy_domains_test.py", "new_path": "timesketch/lib/analyzers/phishy_domains_test.py", "diff": "@@ -3,8 +3,8 @@ from __future__ import unicode_literals\nimport mock\n-from datasketch.minhash import MinHash\nfrom flask import current_app\n+from datasketch.minhash import MinHash\nfrom timesketch.lib.analyzers import phishy_domains\nfrom timesketch.lib.testlib import BaseTest\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/utils.py", "new_path": "timesketch/lib/analyzers/utils.py", "diff": "from __future__ import unicode_literals\n-import numpy\n-\nfrom six.moves import urllib_parse as urlparse\n+import numpy\n+\nfrom timesketch.lib.analyzers import interface\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/charts/manager_test.py", "new_path": "timesketch/lib/charts/manager_test.py", "diff": "@@ -33,7 +33,7 @@ class TestChartManager(BaseTest):\ndef test_get_charts(self):\n\"\"\"Test to get chart class objects.\"\"\"\ncharts = manager.ChartManager.get_charts()\n- chart_list = [x for x in charts]\n+ chart_list = list(charts)\nfirst_chart_tuple = chart_list[0]\nchart_name, chart_class = first_chart_tuple\nself.assertIsInstance(chart_list, list)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/google_auth.py", "new_path": "timesketch/lib/google_auth.py", "diff": "@@ -250,7 +250,7 @@ def validate_jwt(decoded_jwt, expected_issuer, expected_domain=None):\nif issued_at > now:\nraise JwtValidationError('Token was issued in the future')\n- elif expires_at < now:\n+ if expires_at < now:\nraise JwtValidationError('Token has expired')\nexcept KeyError as e:\nraise JwtValidationError('Missing timestamp: {}'.format(e))\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -24,11 +24,12 @@ import io\nimport json\nimport six\n+from elasticsearch.exceptions import RequestError\n+from flask import current_app\n+\nfrom celery import chain\nfrom celery import signals\n-from flask import current_app\nfrom sqlalchemy import create_engine\n-from elasticsearch.exceptions import RequestError\n# Disabled until the project can provide a non-ES native import.\n# from mans_to_es import MansToEs\n" }, { "change_type": "MODIFY", "old_path": "timesketch/models/sketch.py", "new_path": "timesketch/models/sketch.py", "diff": "@@ -17,6 +17,9 @@ from __future__ import unicode_literals\nimport json\n+from flask import current_app\n+from flask import url_for\n+\nfrom sqlalchemy import Column\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import Integer\n@@ -24,9 +27,6 @@ from sqlalchemy import Unicode\nfrom sqlalchemy import UnicodeText\nfrom sqlalchemy.orm import relationship\n-from flask import current_app\n-from flask import url_for\n-\nfrom timesketch.models import BaseModel\nfrom timesketch.models.acl import AccessControlMixin\nfrom timesketch.models.annotations import LabelMixin\n@@ -134,7 +134,8 @@ class Sketch(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\nfor timeline in self.timelines:\ntimeline_status = timeline.get_status.status\nindex_status = timeline.searchindex.get_status.status\n- if (timeline_status or index_status) in ['processing', 'fail', 'archived']:\n+ if (timeline_status or index_status) in (\n+ 'processing', 'fail', 'archived'):\ncontinue\n_timelines.append(timeline)\nreturn _timelines\n" }, { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -25,6 +25,8 @@ import yaml\nimport six\nfrom flask import current_app\n+from werkzeug.exceptions import Forbidden\n+\nfrom flask_migrate import MigrateCommand\nfrom flask_script import Command\nfrom flask_script import Manager\n@@ -33,7 +35,6 @@ from flask_script import Option\nfrom flask_script import prompt_bool\nfrom flask_script import prompt_pass\nfrom sqlalchemy.exc import IntegrityError\n-from werkzeug.exceptions import Forbidden\nfrom timesketch.app import create_app\nfrom timesketch.lib.datastores.elastic import ElasticsearchDataStore\n" }, { "change_type": "MODIFY", "old_path": "timesketch/views/auth.py", "new_path": "timesketch/views/auth.py", "diff": "@@ -25,12 +25,13 @@ from flask import render_template\nfrom flask import request\nfrom flask import session\nfrom flask import url_for\n+\n+from oauthlib import oauth2\n+\nfrom flask_login import current_user\nfrom flask_login import login_user\nfrom flask_login import logout_user\n-from oauthlib import oauth2\n-\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_UNAUTHORIZED\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_OK\n" } ]
Python
Apache License 2.0
google/timesketch
Pinned pylint to version 2.4.x and addressed linter issues (#1252)
263,178
09.06.2020 09:05:33
-7,200
f5f0318594b7fb1dd44b46aa7b0f32c9c6b9f8f1
Added pylint support to tox configuration
[ { "change_type": "MODIFY", "old_path": "tox.ini", "new_path": "tox.ini", "diff": "[tox]\n-envlist = py3\n+envlist = py3{6,7,8},coverage,pylint\n[testenv]\npip_pre = True\n@@ -9,10 +9,17 @@ deps =\nCython\n-rrequirements.txt\n-rtest_requirements.txt\n+ # TODO: remove nose from test_requirements.txt\n+ # nose\n+ # TODO: remove coverage from test_requirements.txt\n+ # coverage: coverage\ncommands =\n- ./run_tests.py\n+ py3{6,7,8}: nosetests -x api_client/python importer_client/python timesketch\n+ coverage: coverage erase\n+ coverage: nosetests --with-coverage --cover-package=timesketch_api_client,timesketch_import_client,timesketch api_client/python importer_client/python timesketch\n-[testenv:py38]\n+[testenv:pylint]\n+skipsdist=True\npip_pre = True\nsetenv =\nPYTHONPATH = {toxinidir}\n@@ -20,6 +27,7 @@ deps =\nCython\n-rrequirements.txt\n-rtest_requirements.txt\n+ # TODO: remove pylint from test_requirements.txt and run_tests.py\n+ # pylint >= 2.4.0, < 2.5.0\ncommands =\n- coverage erase\n- coverage run --source=timesketch --omit=\"*_test*,*__init__*,*test_lib*\" run_tests.py\n+ pylint --rcfile=.pylintrc api_client/python/timesketch_api_client importer_client/python/timesketch_import_client timesketch tests\n" } ]
Python
Apache License 2.0
google/timesketch
Added pylint support to tox configuration (#1258)
263,178
09.06.2020 09:19:33
-7,200
39b7c20d6606f4f42ef22a22dd5cd49250b41c10
Updated pytlint configuration file to version 2.4.x
[ { "change_type": "MODIFY", "old_path": ".pylintrc", "new_path": ".pylintrc", "diff": "-# Pylint 2.1.x - 2.2.x configuration file\n+# Pylint 2.4.x configuration file\n#\n-# This file is generated by l2tdevtools update-dependencies.py, any dependency\n-# related changes should be made in dependencies.ini.\n[MASTER]\n# A comma-separated list of package or module names from where C extensions may\n# be loaded. Extensions are loading into the active Python interpreter and may\n-# run arbitrary code\n+# run arbitrary code.\nextension-pkg-whitelist=\n# Add files or directories to the blacklist. They should be base names, not\n@@ -21,13 +19,21 @@ ignore-patterns=\n# pygtk.require().\n#init-hook=\n-# Use multiple processes to speed up Pylint.\n+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the\n+# number of processors available to use.\njobs=1\n-# List of plugins (as comma separated values of python modules names) to load,\n+# Control the amount of potential inferred values when inferring a single\n+# object. This can help the performance when dealing with large functions or\n+# complex, nested conditions.\n+limit-inference-results=100\n+\n+# List of plugins (as comma separated values of python module names) to load,\n# usually to register additional checkers.\n+# load-plugins=\n# TODO: enable https://github.com/google/timesketch/issues/855\n# load-plugins=pylint.extensions.docparams\n+load-plugins=\n# Pickle collected data for later comparisons.\npersistent=yes\n@@ -35,6 +41,10 @@ persistent=yes\n# Specify a configuration file.\n#rcfile=\n+# When enabled, pylint would attempt to guess common misconfiguration and emit\n+# user-friendly hints instead of false-positive error messages.\n+suggestion-mode=yes\n+\n# Allow loading of arbitrary C extensions. Extensions are imported into the\n# active Python interpreter and may run arbitrary code.\nunsafe-load-any-extension=no\n@@ -43,7 +53,7 @@ unsafe-load-any-extension=no\n[MESSAGES CONTROL]\n# Only show warnings with the listed confidence levels. Leave empty to show\n-# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED\n+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.\nconfidence=\n# Disable the message, report, category or checker with the given id(s). You\n@@ -54,12 +64,8 @@ confidence=\n# you want to run only the similarities checker, you can use \"--disable=all\n# --enable=similarities\". If you want to run only the classes checker, but have\n# no Warning level messages displayed, use \"--disable=all --enable=classes\n-# --disable=W\"\n-#\n-# TODO: per # https://github.com/google/timesketch/issues/855\n-# do not disable invalid-name,no-member\n-disable=\n- assignment-from-none,\n+# --disable=W\".\n+disable=assignment-from-none,\nbad-inline-option,\ndeprecated-pragma,\nduplicate-code,\n@@ -97,28 +103,29 @@ disable=\n# either give multiple identifier separated by comma (,) or put this option\n# multiple time (only on the command line, not in the configuration file where\n# it should appear only once). See also the \"--disable\" option for examples.\n+# enable=c-extension-no-member\nenable=\n[REPORTS]\n-# Python expression which should return a note less than 10 (10 is the highest\n-# note). You have access to the variables errors warning, statement which\n-# respectively contain the number of errors / warnings messages and the total\n-# number of statements analyzed. This is used by the global evaluation report\n-# (RP0004).\n+# Python expression which should return a score less than or equal to 10. You\n+# have access to the variables 'error', 'warning', 'refactor', and 'convention'\n+# which contain the number of messages in each category, as well as 'statement'\n+# which is the total number of statements analyzed. This score is used by the\n+# global evaluation report (RP0004).\nevaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)\n# Template used to display messages. This is a python new-style format string\n-# used to format the message information. See doc for all details\n+# used to format the message information. See doc for all details.\n#msg-template=\n# Set the output format. Available formats are text, parseable, colorized, json\n-# and msvs (visual studio).You can also give a reporter class, eg\n+# and msvs (visual studio). You can also give a reporter class, e.g.\n# mypackage.mymodule.MyReporterClass.\noutput-format=text\n-# Tells whether to display a full report or only the messages\n+# Tells whether to display a full report or only the messages.\nreports=no\n# Activate the evaluation score.\n@@ -131,11 +138,17 @@ score=no\n# Maximum number of nested blocks for function / method body\nmax-nested-blocks=5\n+# Complete name of functions that never returns. When checking for\n+# inconsistent-return-statements if a never returning function is called then\n+# it will be considered as an explicit return statement and no message will be\n+# printed.\n+never-returning-functions=sys.exit\n+\n[VARIABLES]\n# List of additional names supposed to be defined in builtins. Remember that\n-# you should avoid to define new builtins when possible.\n+# you should avoid defining new builtins when possible.\nadditional-builtins=\n# Tells whether unused global variables should be treated as a violation.\n@@ -143,14 +156,15 @@ allow-global-unused-variables=yes\n# List of strings which can identify a callback function by name. A callback\n# name must start or end with one of those strings.\n-callbacks=cb_,_cb\n+callbacks=cb_,\n+ _cb\n-# A regular expression matching the name of dummy variables (i.e. expectedly\n-# not used).\n+# A regular expression matching the name of dummy variables (i.e. expected to\n+# not be used).\ndummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_\n# Argument names that match this expression will be ignored. Default to name\n-# with leading underscore\n+# with leading underscore.\nignored-argument-names=_.*|^ignored_|^unused_\n# Tells whether we should check for unused import in __init__ files.\n@@ -158,7 +172,7 @@ init-import=no\n# List of qualified module names which can have objects that can redefine\n# builtins.\n-redefining-builtins-modules=six.moves,future.builtins\n+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io\n[TYPECHECK]\n@@ -177,6 +191,10 @@ generated-members=\n# mixin class is detected if its name ends with \"mixin\" (case insensitive).\nignore-mixin-members=yes\n+# Tells whether to warn about missing members when the owner of the attribute\n+# is inferred to be None.\n+ignore-none=yes\n+\n# This flag controls whether pylint should warn about no-member and similar\n# checks whenever an opaque object is returned when inferring. The inference\n# can return multiple potential results while evaluating a Python object, but\n@@ -192,7 +210,7 @@ ignored-classes=optparse.Values,thread._local,_thread._local\n# List of module names for which member attributes should not be checked\n# (useful for modules/projects where namespaces are manipulated during runtime\n-# and thus existing member attributes cannot be deduced by static analysis. It\n+# and thus existing member attributes cannot be deduced by static analysis). It\n# supports qualified module names, as well as Unix pattern matching.\nignored-modules=\n@@ -208,69 +226,143 @@ missing-member-hint-distance=1\n# showing a hint for a missing member.\nmissing-member-max-choices=1\n+# List of decorators that change the signature of a decorated function.\n+signature-mutators=\n+\n[LOGGING]\n+# Format style used to check logging format string. `old` means using %\n+# formatting, `new` is for `{}` formatting,and `fstr` is for f-strings.\n+logging-format-style=old\n+\n# Logging modules to check that the string format arguments are in logging\n-# function parameter format\n+# function parameter format.\nlogging-modules=logging\n[BASIC]\n-# Required attributes for module, separated by a comma\n-#required-attributes=\n+# Naming style matching correct argument names.\n+argument-naming-style=snake_case\n-# List of builtins function names that should not be used, separated by a comma\n-bad-functions=map,filter,apply,input\n+# Regular expression matching correct argument names. Overrides argument-\n+# naming-style.\n+#argument-rgx=\n+argument-rgx==[a-z_][a-z0-9_]{2,30}$\n-# Regular expression which should only match correct module names\n-module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$\n+# Naming style matching correct attribute names.\n+attr-naming-style=snake_case\n-# Regular expression which should only match correct module level names\n-const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$\n+# Regular expression matching correct attribute names. Overrides attr-naming-\n+# style.\n+#attr-rgx=\n+attr-rgx=[a-z_][a-z0-9_]{2,30}$\n-# Regular expression which should only match correct class names\n+# Bad variable names which should always be refused, separated by a comma.\n+bad-names=foo,\n+ bar,\n+ baz,\n+ toto,\n+ tutu,\n+ tata\n+\n+# Naming style matching correct class attribute names.\n+class-attribute-naming-style=any\n+\n+# Regular expression matching correct class attribute names. Overrides class-\n+# attribute-naming-style.\n+#class-attribute-rgx=\n+\n+# Naming style matching correct class names.\n+class-naming-style=PascalCase\n+\n+# Regular expression matching correct class names. Overrides class-naming-\n+# style.\n+#class-rgx=\nclass-rgx=[A-Z_][a-zA-Z0-9]+$\n-# Regular expression which should only match correct function names\n+# Naming style matching correct constant names.\n+const-naming-style=UPPER_CASE\n+\n+# Regular expression matching correct constant names. Overrides const-naming-\n+# style.\n+#const-rgx=\n+const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$\n+\n+# Minimum line length for functions/classes that require docstrings, shorter\n+# ones are exempt.\n+# docstring-min-length=-1\n+docstring-min-length=25\n+\n+# Naming style matching correct function names.\n+function-naming-style=snake_case\n+\n+# Regular expression matching correct function names. Overrides function-\n+# naming-style.\n+#function-rgx=\nfunction-rgx=[a-z_][a-z0-9_]{2,30}$\n-# Regular expression which should only match correct method names\n-method-rgx=[a-z_][a-z0-9_]{2,30}$\n+# Good variable names which should always be accepted, separated by a comma.\n+good-names=i,\n+ j,\n+ k,\n+ ex,\n+ Run,\n+ _\n-# Regular expression which should only match correct instance attribute names\n-attr-rgx=[a-z_][a-z0-9_]{2,30}$\n+# Include a hint for the correct naming format with invalid-name.\n+include-naming-hint=no\n+\n+# Naming style matching correct inline iteration names.\n+inlinevar-naming-style=any\n-# Regular expression which should only match correct argument names\n-argument-rgx=[a-z_][a-z0-9_]{2,30}$\n+# Regular expression matching correct inline iteration names. Overrides\n+# inlinevar-naming-style.\n+#inlinevar-rgx=\n-# Regular expression which should only match correct variable names\n-variable-rgx=[a-z_][a-z0-9_]{2,30}$\n+# Naming style matching correct method names.\n+method-naming-style=snake_case\n-# Regular expression which should only match correct list comprehension /\n-# generator expression variable names\n-inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$\n+# Regular expression matching correct method names. Overrides method-naming-\n+# style.\n+#method-rgx=\n-# Good variable names which should always be accepted, separated by a comma\n-good-names=i,j,k,ex,Run,_\n+# Naming style matching correct module names.\n+module-naming-style=snake_case\n-# Bad variable names which should always be refused, separated by a comma\n-bad-names=foo,bar,baz,toto,tutu,tata\n+# Regular expression matching correct module names. Overrides module-naming-\n+# style.\n+#module-rgx=\n-# Regular expression which should only match functions or classes name which do\n-# not require a docstring\n+# Colon-delimited sets of names that determine each other's naming style when\n+# the name regexes allow several styles.\n+name-group=\n+\n+# Regular expression which should only match function or class names that do\n+# not require a docstring.\n+# no-docstring-rgx=^_\nno-docstring-rgx=__.*__\n-# Minimum line length for functions/classes that require docstrings, shorter\n-# ones are exempt.\n-docstring-min-length=25\n+# List of decorators that produce properties, such as abc.abstractproperty. Add\n+# to this list to register other decorators that produce valid properties.\n+# These decorators are taken in consideration only for invalid-name.\n+property-classes=abc.abstractproperty\n+\n+# Naming style matching correct variable names.\n+variable-naming-style=snake_case\n+\n+# Regular expression matching correct variable names. Overrides variable-\n+# naming-style.\n+#variable-rgx=\n[MISCELLANEOUS]\n# List of note tags to take in consideration, separated by a comma.\n-notes=FIXME,XXX,TODO\n+notes=FIXME,\n+ XXX,\n+ TODO\n[FORMAT]\n@@ -292,14 +384,15 @@ indent-string=' '\n# max-line-length=100\nmax-line-length=80\n-# Maximum number of lines in a module\n+# Maximum number of lines in a module.\nmax-module-lines=1000\n# List of optional constructs for which whitespace checking is disabled. `dict-\n# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\\n222: 2}.\n# `trailing-comma` allows a space between comma and closing bracket: (a, ).\n# `empty-line` allows space-only lines.\n-no-space-check=trailing-comma,dict-separator\n+no-space-check=trailing-comma,\n+ dict-separator\n# Allow the body of a class to be on the same line as the declaration if body\n# contains single statement.\n@@ -312,17 +405,26 @@ single-line-if-stmt=no\n[SPELLING]\n-# Spelling dictionary name. Available dictionaries: en_US (myspell).\n+# Limits count of emitted suggestions for spelling mistakes.\n+max-spelling-suggestions=4\n+\n+# Spelling dictionary name. Available dictionaries: en_NA (myspell), en_NZ\n+# (myspell), en_ZM (myspell), en_CA (myspell), en_GH (myspell), en_IN\n+# (myspell), en_TT (myspell), en_BS (myspell), en_DK (myspell), en_MW\n+# (myspell), en_ZW (myspell), en_BW (myspell), en_ZA (myspell), en_BZ\n+# (myspell), en_JM (myspell), en_US (myspell), en_PH (myspell), en_GB\n+# (myspell), en_SG (myspell), en_IE (myspell), en_HK (myspell), en_AU\n+# (myspell), en_AG (myspell), en_NG (myspell).\nspelling-dict=\n# List of comma separated words that should not be checked.\nspelling-ignore-words=\n-# A path to a file that contains private dictionary; one word per line.\n+# A path to a file that contains the private dictionary; one word per line.\nspelling-private-dict-file=\n-# Tells whether to store unknown words to indicated private dictionary in\n-# --spelling-private-dict-file option instead of raising a message.\n+# Tells whether to store unknown words to the private dictionary (see the\n+# --spelling-private-dict-file option) instead of raising a message.\nspelling-store-unknown-words=no\n@@ -341,22 +443,30 @@ ignore-imports=no\nmin-similarity-lines=4\n+[STRING]\n+\n+# This flag controls whether the implicit-str-concat-in-sequence should\n+# generate a warning on implicit string concatenation in sequences defined over\n+# several lines.\n+check-str-concat-over-line-jumps=no\n+\n+\n[DESIGN]\n-# Maximum number of arguments for function / method\n+# Maximum number of arguments for function / method.\n# max-args=5\nmax-args=10\n# Maximum number of attributes for a class (see R0902).\nmax-attributes=7\n-# Maximum number of boolean expressions in a if statement\n+# Maximum number of boolean expressions in an if statement (see R0916).\nmax-bool-expr=5\n-# Maximum number of branch for function / method body\n+# Maximum number of branch for function / method body.\nmax-branches=12\n-# Maximum number of locals for function / method body\n+# Maximum number of locals for function / method body.\nmax-locals=15\n# Maximum number of parents for a class (see R0901).\n@@ -365,10 +475,10 @@ max-parents=7\n# Maximum number of public methods for a class (see R0904).\nmax-public-methods=20\n-# Maximum number of return / yield for function / method body\n+# Maximum number of return / yield for function / method body.\nmax-returns=6\n-# Maximum number of statements in function / method body\n+# Maximum number of statements in function / method body.\nmax-statements=50\n# Minimum number of public methods for a class (see R0903).\n@@ -378,21 +488,32 @@ min-public-methods=2\n[CLASSES]\n# List of method names used to declare (i.e. assign) instance attributes.\n-defining-attr-methods=__init__,__new__,setUp\n+defining-attr-methods=__init__,\n+ __new__,\n+ setUp,\n+ __post_init__\n# List of member names, which should be excluded from the protected access\n# warning.\n-exclude-protected=_asdict,_fields,_replace,_source,_make\n+exclude-protected=_asdict,\n+ _fields,\n+ _replace,\n+ _source,\n+ _make\n# List of valid names for the first argument in a class method.\nvalid-classmethod-first-arg=cls\n# List of valid names for the first argument in a metaclass class method.\n-valid-metaclass-classmethod-first-arg=mcs\n+valid-metaclass-classmethod-first-arg=cls\n[IMPORTS]\n+# List of modules that can be imported at any level, not just the top level\n+# one.\n+allow-any-import-level=\n+\n# Allow wildcard imports from modules that define __all__.\nallow-wildcard-with-all=no\n@@ -401,19 +522,19 @@ allow-wildcard-with-all=no\n# only in one or another interpreter, leading to false positives when analysed.\nanalyse-fallback-blocks=no\n-# Deprecated modules which should not be used, separated by a comma\n+# Deprecated modules which should not be used, separated by a comma.\ndeprecated-modules=optparse,tkinter.tix\n# Create a graph of external dependencies in the given file (report RP0402 must\n-# not be disabled)\n+# not be disabled).\next-import-graph=\n# Create a graph of every (i.e. internal and external) dependencies in the\n-# given file (report RP0402 must not be disabled)\n+# given file (report RP0402 must not be disabled).\nimport-graph=\n# Create a graph of internal dependencies in the given file (report RP0402 must\n-# not be disabled)\n+# not be disabled).\nint-import-graph=\n# Force import order to recognize a module as part of the standard\n@@ -423,9 +544,13 @@ known-standard-library=\n# Force import order to recognize a module as part of a third party library.\nknown-third-party=enchant\n+# Couples of modules and preferred modules, separated by a comma.\n+preferred-modules=\n+\n[EXCEPTIONS]\n# Exceptions that will emit a warning when being caught. Defaults to\n-# \"Exception\"\n-overgeneral-exceptions=Exception\n+# \"BaseException, Exception\".\n+overgeneral-exceptions=BaseException,\n+ Exception\n" } ]
Python
Apache License 2.0
google/timesketch
Updated pytlint configuration file to version 2.4.x (#1253) Co-authored-by: Johan Berggren <jberggren@gmail.com>
263,133
10.06.2020 10:06:50
0
2e704828617fb2080c6b69d1a42640af5643bc95
Making minor changes to the API client's behavior in tagging events
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/error.py", "new_path": "api_client/python/timesketch_api_client/error.py", "diff": "@@ -70,6 +70,7 @@ def get_response_json(response, logger):\nreturn response.json()\nexcept json.JSONDecodeError as e:\nlogger.error('Unable to decode response: {0!s}'.format(e))\n+\nreturn {}\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": "@@ -1121,7 +1121,7 @@ class Sketch(resource.BaseResource):\nRuntimeError: if the sketch is archived.\nReturns:\n- A boolean indicating whether the operation was successful or not.\n+ A dict with the results from the tagging operation.\n\"\"\"\nif self.is_archived():\nraise RuntimeError(\n@@ -1140,7 +1140,18 @@ class Sketch(resource.BaseResource):\nresource_url = '{0:s}/sketches/{1:d}/event/tagging/'.format(\nself.api.api_root, self.id)\nresponse = self.api.session.post(resource_url, json=form_data)\n- return error.check_return_status(response, logger)\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ return {\n+ 'number_of_events': len(events),\n+ 'number_of_events_with_tag': 0,\n+ 'success': status\n+ }\n+\n+ response_json = error.get_response_json(response, logger)\n+ meta = response_json.get('meta', {})\n+ meta['number_of_events_sent'] = len(events)\n+ return meta\ndef search_by_label(self, label_name, as_pandas=False):\n\"\"\"Searches for all events containing a given label.\n" } ]
Python
Apache License 2.0
google/timesketch
Making minor changes to the API client's behavior in tagging events
263,133
11.06.2020 15:31:34
0
5fc62f7d8e38997e005d52e0b5ac99e94f1e339a
Changing the behavior of the API
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -1109,12 +1109,14 @@ class Sketch(resource.BaseResource):\nresponse = self.api.session.post(resource_url, json=form_data)\nreturn error.get_response_json(response, logger)\n- def tag_events(self, events, tags):\n+ def tag_events(self, events, tags, verbose=False):\n\"\"\"Tags one or more events with a list of tags.\nArgs:\nevents: Array of JSON objects representing events.\ntags: List of tags (str) to add to the events.\n+ verbose: Bool that determines whether extra information\n+ is added to the meta dict that gets returned.\nRaises:\nValueError: if tags is not a list of strings.\n@@ -1135,7 +1137,8 @@ class Sketch(resource.BaseResource):\nform_data = {\n'tag_string': json.dumps(tags),\n- 'events': events\n+ 'events': events,\n+ 'verbose': verbose,\n}\nresource_url = '{0:s}/sketches/{1:d}/event/tagging/'.format(\nself.api.api_root, self.id)\n@@ -1150,7 +1153,7 @@ class Sketch(resource.BaseResource):\nresponse_json = error.get_response_json(response, logger)\nmeta = response_json.get('meta', {})\n- meta['number_of_events_sent'] = len(events)\n+ meta['total_number_of_events_sent_by_client'] = len(events)\nreturn meta\ndef search_by_label(self, label_name, as_pandas=False):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/__init__.py", "new_path": "timesketch/api/v1/resources/__init__.py", "diff": "@@ -17,6 +17,8 @@ The timesketch API is a RESTful API that exposes the following resources:\n\"\"\"\nfrom __future__ import unicode_literals\n+import logging\n+\nfrom flask import current_app\nfrom flask import jsonify\nfrom flask_restful import fields\n@@ -26,6 +28,12 @@ from timesketch.lib.definitions import HTTP_STATUS_CODE_OK\nfrom timesketch.lib.datastores.elastic import ElasticsearchDataStore\n+logging.basicConfig(\n+ format='%(asctime)s %(levelname)-8s %(message)s',\n+ level=logging.INFO,\n+ datefmt='%Y-%m-%d %H:%M:%S')\n+\n+\nclass ResourceMixin(object):\n\"\"\"Mixin for API resources.\"\"\"\n# Schemas for database model resources\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/event.py", "new_path": "timesketch/api/v1/resources/event.py", "diff": "@@ -17,10 +17,14 @@ import codecs\nimport hashlib\nimport json\nimport logging\n+import math\nimport time\nimport six\nimport dateutil\n+from elasticsearch.exceptions import RequestError\n+import numpy as np\n+import pandas as pd\nfrom flask import jsonify\nfrom flask import request\n@@ -47,6 +51,45 @@ from timesketch.models.sketch import Timeline\nlogger = logging.getLogger('api_resources')\n+def _tag_event(row, tag_dict, tags_to_add, datastore, flush_interval):\n+ \"\"\"Tag each event from a dataframe with tags.\n+\n+ Args:\n+ row (np.Series): a single row of data with existing tags and\n+ information about the event in order to be able to add\n+ tags to it.\n+ tag_dict (dict): a dict that contains information to be returned\n+ by the API call to the user.\n+ tags_to_add (list[str]): a list of strings of tags to add to each\n+ event.\n+ datastore (elastic.ElasticsearchDataStore): the datastore object.\n+ flush_interval (int): the number of events to import before a bulk\n+ update is done with the datastore.\n+ \"\"\"\n+ tag_dict['events_processed_by_api'] += 1\n+ existing_tags = set()\n+\n+ if 'tag' in row:\n+ tag = row['tag']\n+ if isinstance(tag, (list, tuple)):\n+ existing_tags = set(tag)\n+\n+ new_tags = list(set().union(existing_tags, set(tags_to_add)))\n+ else:\n+ new_tags = tags_to_add\n+\n+ if set(existing_tags) == set(new_tags):\n+ return\n+\n+ datastore.import_event(\n+ index_name=row['_index'], event_type=row['_type'],\n+ event_id=row['_id'], event={'tag': new_tags},\n+ flush_interval=flush_interval)\n+\n+ tag_dict['tags_applied'] += len(new_tags)\n+ tag_dict['number_of_events_with_added_tags'] += 1\n+\n+\nclass EventCreateResource(resources.ResourceMixin, Resource):\n\"\"\"Resource to create an annotation for an event.\"\"\"\n@@ -244,6 +287,12 @@ class EventResource(resources.ResourceMixin, Resource):\nclass EventTaggingResource(resources.ResourceMixin, Resource):\n\"\"\"Resource to fetch and set tags to an event.\"\"\"\n+ # The number of events to bulk together for each query.\n+ EVENT_CHUNK_SIZE = 1000\n+\n+ # The maximum number of events to tag in a single request.\n+ MAX_EVENTS_TO_TAG = 100000\n+\n@login_required\ndef post(self, sketch_id):\n\"\"\"Handles POST request to the resource.\n@@ -270,8 +319,9 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\nform = request.data\ntag_dict = {\n- 'event_count': 0,\n- 'tag_count': 0,\n+ 'events_processed_by_api': 0,\n+ 'number_of_events_with_added_tags': 0,\n+ 'tags_applied': 0,\n}\ndatastore = self.datastore\n@@ -281,6 +331,7 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to read the tags, with error: {0!s}'.format(e))\n+\nif not isinstance(tags_to_add, list):\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Tags need to be a list')\n@@ -291,43 +342,98 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\n'Tags need to be a list of strings')\nevents = form.get('events', [])\n- for _event in events:\n+ event_df = pd.DataFrame(events)\n+ tag_df = pd.DataFrame()\n+\n+ event_size = event_df.shape[0]\n+ if event_size > self.MAX_EVENTS_TO_TAG:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Cannot tag more than {0:d} events in a single '\n+ 'request'.format(self.MAX_EVENTS_TO_TAG))\n+\n+ tag_dict['number_of_events_passed_to_api'] = event_size\n+\n+ verbose = form.get('verbose', False)\n+ if verbose:\n+ tag_dict['number_of_indices'] = len(event_df['_index'].unique())\n+ time_tag_gathering_start = time.time()\n+\n+ for _index in event_df['_index'].unique():\n+ query_filter = {\n+ 'time_start': None,\n+ 'time_end': None,\n+ 'indices': [_index],\n+ }\n+\n+ index_slice = event_df[event_df['_index'] == _index]\n+ index_size = index_slice.shape[0]\n+ if verbose:\n+ tag_dict.setdefault('index_count', {})\n+ tag_dict['index_count'][_index] = index_size\n+\n+ if index_size <= self.EVENT_CHUNK_SIZE:\n+ chunks = 1\n+ else:\n+ chunks = math.ceil(index_size / self.EVENT_CHUNK_SIZE)\n+\n+ tags = []\n+ for index_chunk in np.array_split(\n+ index_slice['_id'].unique(), chunks):\n+ should_list = [{'match': {'_id': x}} for x in index_chunk]\nquery = {\n'query': {\n'bool': {\n- 'filter': {\n- 'term': {\n- '_id': _event['_id'],\n- }\n+ 'should': should_list\n}\n}\n}\n- }\n- results = datastore.client.search(\n- index=[_event['_index']], body=query)\n-\n- ds_events = results['hits']['hits']\n- if len(ds_events) != 1:\n- logger.error(\n- 'Unable to tag event: {0:s}, couldn\\'t find the '\n- 'event.'.format(_event['_id']))\n+ try:\n+ for result in datastore.search_stream(\n+ sketch_id=sketch.id, query_dsl=json.dumps(query),\n+ indices=[_index], return_fields=['tag'],\n+ query_filter=query_filter, enable_scroll=False):\n+ tag = result.get('_source', {}).get('tag', [])\n+ if not tag:\ncontinue\n+ tags.append({'_id': result.get('_id'), 'tag': tag})\n+ except RequestError as e:\n+ logger.error('Unable to query for events, {0!s}'.format(e))\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to query events, {0!s}'.format(e))\n- source = ds_events[0].get('_source', {})\n- existing_tags = source.get('tag', [])\n- new_tags = list(set().union(existing_tags, tags_to_add))\n-\n- if set(existing_tags) == set(new_tags):\n+ if not tags:\ncontinue\n+ tag_df = pd.concat([tag_df, pd.DataFrame(tags)])\n- datastore.import_event(\n- index_name=_event['_index'], event_type=_event['_type'],\n- event_id=_event['_id'], event={'tag': new_tags})\n+ event_df = event_df.merge(tag_df, on='_id', how='left')\n- tag_dict['event_count'] += 1\n- tag_dict['tag_count'] += len(new_tags)\n+ if verbose:\n+ tag_dict[\n+ 'time_to_gather_tags'] = time.time() - time_tag_gathering_start\n+ tag_dict['number_of_events'] = len(events)\n+ if 'tag' in event_df:\n+ current_tag_events = event_df[~event_df['tag'].isna()].shape[0]\n+ tag_dict['number_of_events_with_tags'] = current_tag_events\n+ else:\n+ tag_dict['number_of_events_with_tags'] = 0\n+\n+ tag_dict['tags_to_add'] = tags_to_add\n+ time_tag_start = time.time()\n+ if event_size > datastore.DEFAULT_FLUSH_INTERVAL:\n+ flush_interval = 10000\n+ else:\n+ flush_interval = datastore.DEFAULT_FLUSH_INTERVAL\n+ _ = event_df.apply(\n+ _tag_event, axis=1, tag_dict=tag_dict, tags_to_add=tags_to_add,\n+ datastore=datastore, flush_interval=flush_interval)\ndatastore.flush_queued_events()\n+\n+ if verbose:\n+ tag_dict['time_to_tag'] = time.time() - time_tag_start\n+\nschema = {\n'meta': tag_dict,\n'objects': []}\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/datastores/elastic.py", "new_path": "timesketch/lib/datastores/elastic.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Elasticsearch datastore.\"\"\"\n-\nfrom __future__ import unicode_literals\nfrom collections import Counter\n@@ -356,7 +355,7 @@ class ElasticsearchDataStore(object):\ndef search_stream(self, sketch_id=None, query_string=None,\nquery_filter=None, query_dsl=None, indices=None,\n- return_fields=None):\n+ return_fields=None, enable_scroll=True):\n\"\"\"Search ElasticSearch. This will take a query string from the UI\ntogether with a filter definition. Based on this it will execute the\nsearch request on ElasticSearch and get result back.\n@@ -368,6 +367,7 @@ class ElasticsearchDataStore(object):\nquery_dsl: Dictionary containing Elasticsearch DSL query\nindices: List of indices to query\nreturn_fields: List of fields to return\n+ enable_scroll: Boolean determing whether scrolling is enabled.\nReturns:\nGenerator of event documents in JSON format\n@@ -386,10 +386,14 @@ class ElasticsearchDataStore(object):\nquery_filter=query_filter,\nindices=indices,\nreturn_fields=return_fields,\n- enable_scroll=True)\n+ enable_scroll=enable_scroll)\n+ if enable_scroll:\nscroll_id = result['_scroll_id']\nscroll_size = result['hits']['total']\n+ else:\n+ scroll_id = None\n+ scroll_size = 0\n# Elasticsearch version 7.x returns total hits as a dictionary.\n# TODO: Refactor when version 6.x has been deprecated.\n" } ]
Python
Apache License 2.0
google/timesketch
Changing the behavior of the API
263,133
12.06.2020 07:14:35
0
5272d9a706d426186727e20cbaff3e7b4aa557b8
Adding a safety guard if no tags are there
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/event.py", "new_path": "timesketch/api/v1/resources/event.py", "diff": "@@ -407,6 +407,7 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\ncontinue\ntag_df = pd.concat([tag_df, pd.DataFrame(tags)])\n+ if tag_df.shape[0]:\nevent_df = event_df.merge(tag_df, on='_id', how='left')\nif verbose:\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a safety guard if no tags are there
263,133
12.06.2020 08:04:45
0
265d56f8170327a6e326f39d3b1d4fdf1495d5db
Adding some checks and balances
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/event.py", "new_path": "timesketch/api/v1/resources/event.py", "diff": "@@ -343,6 +343,22 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\nevents = form.get('events', [])\nevent_df = pd.DataFrame(events)\n+\n+ for field in ['_id', '_type', '_index']:\n+ if field not in event_df:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Events need to have a [{0:s}] field associated '\n+ 'to it.'.format(field))\n+ if any(event_df[field].isna()):\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'All events need to have a [{0:s}] field '\n+ 'set, it cannot have a non-value.'.format(field))\n+\n+ # Remove any potential extra fields from the events.\n+ event_df = event_df[['_id', '_type', '_index']]\n+\ntag_df = pd.DataFrame()\nevent_size = event_df.shape[0]\n@@ -354,6 +370,8 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\ntag_dict['number_of_events_passed_to_api'] = event_size\n+ errors = []\n+\nverbose = form.get('verbose', False)\nif verbose:\ntag_dict['number_of_indices'] = len(event_df['_index'].unique())\n@@ -399,6 +417,8 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\ntags.append({'_id': result.get('_id'), 'tag': tag})\nexcept RequestError as e:\nlogger.error('Unable to query for events, {0!s}'.format(e))\n+ errors.append(\n+ 'Unable to query for events, {0!s}'.format(e))\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to query events, {0!s}'.format(e))\n@@ -414,6 +434,10 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\ntag_dict[\n'time_to_gather_tags'] = time.time() - time_tag_gathering_start\ntag_dict['number_of_events'] = len(events)\n+\n+ if tag_df.shape[0]:\n+ tag_dict['number_of_events_in_tag_frame'] = tag_df.shape[0]\n+\nif 'tag' in event_df:\ncurrent_tag_events = event_df[~event_df['tag'].isna()].shape[0]\ntag_dict['number_of_events_with_tags'] = current_tag_events\n@@ -435,6 +459,9 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\nif verbose:\ntag_dict['time_to_tag'] = time.time() - time_tag_start\n+ if errors:\n+ tag_dict['errors'] = errors\n+\nschema = {\n'meta': tag_dict,\n'objects': []}\n" } ]
Python
Apache License 2.0
google/timesketch
Adding some checks and balances
263,133
12.06.2020 10:55:25
0
971bd4c0745f91b52cf7dac185dc825d529589a6
Making changes to the search criteria
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/event.py", "new_path": "timesketch/api/v1/resources/event.py", "diff": "@@ -293,6 +293,9 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\n# The maximum number of events to tag in a single request.\nMAX_EVENTS_TO_TAG = 100000\n+ # The size of the buffer before a bulk update in ES takes place.\n+ BUFFER_SIZE_FOR_ES_BULK_UPDATES = 10000\n+\n@login_required\ndef post(self, sketch_id):\n\"\"\"Handles POST request to the resource.\n@@ -378,14 +381,9 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\ntime_tag_gathering_start = time.time()\nfor _index in event_df['_index'].unique():\n- query_filter = {\n- 'time_start': None,\n- 'time_end': None,\n- 'indices': [_index],\n- }\n-\nindex_slice = event_df[event_df['_index'] == _index]\nindex_size = index_slice.shape[0]\n+\nif verbose:\ntag_dict.setdefault('index_count', {})\ntag_dict['index_count'][_index] = index_size\n@@ -399,22 +397,35 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\nfor index_chunk in np.array_split(\nindex_slice['_id'].unique(), chunks):\nshould_list = [{'match': {'_id': x}} for x in index_chunk]\n- query = {\n+ query_body = {\n'query': {\n'bool': {\n'should': should_list\n}\n}\n}\n+\n+ size = len(should_list) + 100\n+ query_body['size'] = size\n+ query_body['terminate_after'] = size\n+\ntry:\n- for result in datastore.search_stream(\n- sketch_id=sketch.id, query_dsl=json.dumps(query),\n- indices=[_index], return_fields=['tag'],\n- query_filter=query_filter, enable_scroll=False):\n- tag = result.get('_source', {}).get('tag', [])\n- if not tag:\n- continue\n- tags.append({'_id': result.get('_id'), 'tag': tag})\n+ # pylint: disable=unexpected-keyword-arg\n+ if datastore.version.startswith('6'):\n+ search = datastore.client.search(\n+ body=json.dumps(query_body),\n+ index=[_index],\n+ _source_include=['tag'],\n+ search_type='query_then_fetch'\n+ )\n+ else:\n+ search = datastore.client.search(\n+ body=json.dumps(query_body),\n+ index=[_index],\n+ _source_includes=['tag'],\n+ search_type='query_then_fetch'\n+ )\n+\nexcept RequestError as e:\nlogger.error('Unable to query for events, {0!s}'.format(e))\nerrors.append(\n@@ -423,6 +434,12 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to query events, {0!s}'.format(e))\n+ for result in search['hits']['hits']:\n+ tag = result.get('_source', {}).get('tag', [])\n+ if not tag:\n+ continue\n+ tags.append({'_id': result.get('_id'), 'tag': tag})\n+\nif not tags:\ncontinue\ntag_df = pd.concat([tag_df, pd.DataFrame(tags)])\n@@ -448,7 +465,7 @@ class EventTaggingResource(resources.ResourceMixin, Resource):\ntime_tag_start = time.time()\nif event_size > datastore.DEFAULT_FLUSH_INTERVAL:\n- flush_interval = 10000\n+ flush_interval = self.BUFFER_SIZE_FOR_ES_BULK_UPDATES\nelse:\nflush_interval = datastore.DEFAULT_FLUSH_INTERVAL\n_ = event_df.apply(\n" } ]
Python
Apache License 2.0
google/timesketch
Making changes to the search criteria
263,096
17.06.2020 14:43:42
-7,200
17dfc06762bcf26e2c3cdbbf2dbaae0af09817a1
Document location of frontend code on docker Mention the location of the frontend code in docker
[ { "change_type": "MODIFY", "old_path": "docs/Developers-Guide.md", "new_path": "docs/Developers-Guide.md", "diff": "@@ -23,7 +23,7 @@ Install Node.js and Yarn\n$ apt-get update && apt-get install nodejs yarn\n-Cd to timesketch repository root (folder that contains `package.json`)\n+Cd to timesketch repository root (folder that contains `package.json` - on docker it is: `/usr/local/src/timesketch/timesketch/frontend`)\nand install Node.js packages (this will create `node_modules/` folder in the\ncurrent directory and install packages from `package.json` there)\n" } ]
Python
Apache License 2.0
google/timesketch
Document location of frontend code on docker Mention the location of the frontend code in docker
263,096
17.06.2020 21:36:35
-7,200
c99ea848a39d22cb4347606b6cba97b98ce627fd
Fix method docstring (copy paste error) Guess there was a copy paste error in this PR: As the method does not return user info.
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/information.py", "new_path": "timesketch/api/v1/resources/information.py", "diff": "@@ -30,7 +30,7 @@ class VersionResource(resources.ResourceMixin, Resource):\n\"\"\"Handles GET request to the resource.\nReturns:\n- List of usernames\n+ JSON object including version info\n\"\"\"\nschema = {\n'meta': {\n" } ]
Python
Apache License 2.0
google/timesketch
Fix method docstring (copy paste error) Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47 As the method does not return user info.
263,093
25.06.2020 16:20:28
-7,200
a51b7e5e74d7d911cbfb134aa29f5ab78aa17211
Correct count
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/sketch.py", "new_path": "timesketch/api/v1/resources/sketch.py", "diff": "@@ -157,11 +157,18 @@ class SketchResource(resources.ResourceMixin, Resource):\n'Unable to find index in datastore, with error: '\n'{0!s}'.format(e))\n+ # Stats for index. Num docs per shard and size on disk.\nfor index_name, stats in es_stats.get('indices', {}).items():\n- stats_per_index[index_name] = {\n- 'count': stats.get('total', {}).get('docs', {}).get('count', 0),\n- 'bytes': stats.get(\n+ doc_count_all_shards = stats.get(\n+ 'total', {}).get('docs', {}).get('count', 0)\n+ bytes_on_disk = stats.get(\n'total', {}).get('store', {}).get('size_in_bytes', 0)\n+ num_shards = stats.get('_shards', {}).get('total', 1)\n+ doc_count = int(doc_count_all_shards / num_shards)\n+\n+ stats_per_index[index_name] = {\n+ 'count': doc_count,\n+ 'bytes': bytes_on_disk\n}\nif not sketch_indices:\n" } ]
Python
Apache License 2.0
google/timesketch
Correct count
263,100
20.04.2020 14:15:34
0
76625d975997ec8911515bccdc5e3dd0cb21f422
Safe Browsing analyzer
[ { "change_type": "MODIFY", "old_path": "requirements.txt", "new_path": "requirements.txt", "diff": "@@ -15,6 +15,7 @@ flask_wtf==0.14.2\ngoogle-auth==1.7.0\ngoogle_auth_oauthlib==0.4.1\ngunicorn==19.10.0 # Note: Last version to support py2\n+httmock==1.3.0\nneo4jrestclient==2.1.1\nnumpy==1.17.5\noauthlib==3.1.0\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/__init__.py", "new_path": "timesketch/lib/analyzers/__init__.py", "diff": "@@ -23,6 +23,7 @@ from timesketch.lib.analyzers import expert_sessionizers\nfrom timesketch.lib.analyzers import feature_extraction\nfrom timesketch.lib.analyzers import login\nfrom timesketch.lib.analyzers import phishy_domains\n+from timesketch.lib.analyzers import safebrowsing\nfrom timesketch.lib.analyzers import sessionizer\nfrom timesketch.lib.analyzers import sigma_tagger\nfrom timesketch.lib.analyzers import similarity_scorer\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/safebrowsing.py", "diff": "+\"\"\"Sketch analyzer plugin for the Safe Browsing API.\"\"\"\n+from __future__ import unicode_literals\n+\n+import fnmatch\n+import logging\n+import re\n+\n+import pkg_resources\n+import requests\n+from flask import current_app\n+\n+from timesketch.lib.analyzers import interface, manager\n+\n+\n+class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n+ \"\"\"Sketch analyzer for Safe Browsing.\"\"\"\n+\n+ NAME = 'safebrowsing'\n+\n+ _SAFE_BROWSING_BULK_LIMIT = 500\n+ _URL_WHITELIST_CONFIG = 'safebrowsing_whitelist.yaml'\n+ _SAFEBROWSING_ENTRY_KEEP = frozenset(\n+ [\n+ 'platformType',\n+ 'threatType',\n+ ],\n+ )\n+\n+ _URL_BEGINNING_RE = re.compile(r'(http(s|):\\/\\/\\S*)')\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+ super(SafeBrowsingSketchPlugin, self).__init__(index_name, sketch_id)\n+\n+ self._safebrowsing_api_key = current_app.config.get(\n+ 'SAFEBROWSING_API_KEY')\n+\n+ self._google_client_id = current_app.config.get(\n+ 'SAFEBROWSING_CLIENT_ID',\n+ 'Timesketch',\n+ )\n+\n+ self._google_client_version = current_app.config.get(\n+ 'SAFEBROWSING_CLIENT_VERSION',\n+ pkg_resources.get_distribution('timesketch').version,\n+ )\n+\n+ def _is_url_whitelisted(self, url, whitelist):\n+ \"\"\"Does a glob-match against the whitelist.\n+\n+ Args:\n+ url: The url\n+ whitelist: The whitelist, list-like\n+ Returns:\n+ Boolean with the result\n+ \"\"\"\n+\n+ for url_pattern in whitelist:\n+ if fnmatch.fnmatchcase(url, url_pattern):\n+ return True\n+\n+ return False\n+\n+ def _do_safebrowsing_lookup(self, urls, platforms, types):\n+ \"\"\"URL lookup against the Safe Browsing API.\n+\n+ Args:\n+ urls: URLs\n+ platforms: platformTypes field of threatInfo\n+ types: threatTypes field of threatInfo\n+ Returns:\n+ Dict of URLs with the hits\n+ \"\"\"\n+ results = {}\n+\n+ endpoint = 'https://safebrowsing.googleapis.com/v4/threatMatches:find'\n+ api_client = {\n+ 'clientId': self._google_client_id,\n+ 'clientVersion': self._google_client_version,\n+ }\n+\n+ for i in range(0, len(urls), self._SAFE_BROWSING_BULK_LIMIT):\n+ body = {\n+ 'client': api_client,\n+ 'threatInfo': {\n+ 'platformTypes': platforms,\n+ 'threatTypes': types,\n+ 'threatEntryTypes': ['URL'],\n+ 'threatEntries': [\n+ {'url': url}\n+ for url in urls[i:i + self._SAFE_BROWSING_BULK_LIMIT]\n+ ],\n+ },\n+ }\n+\n+ r = requests.post(\n+ endpoint,\n+ params={'key': self._safebrowsing_api_key},\n+ json=body,\n+ )\n+\n+ r.raise_for_status()\n+\n+ result = r.json()\n+ if result and 'matches' in result:\n+ for match in result['matches']:\n+ threat_result = match.copy()\n+\n+ # Keeping only interesting keys\n+ for key in match.keys():\n+ if key not in self._SAFEBROWSING_ENTRY_KEEP:\n+ threat_result.pop(key)\n+\n+ results[match['threat']['url']] = threat_result\n+\n+ return results\n+\n+ def _sanitize_url(self, url_entry):\n+ \"\"\"Finds http[s]:// in 'url_entry' and returns its content from there.\n+\n+ Args:\n+ url_entry: a URL, with some other characters before and after\n+\n+ Returns:\n+ String with the URL\n+ \"\"\"\n+ m = self._URL_BEGINNING_RE.search(url_entry)\n+\n+ if m:\n+ return m.group(1)\n+\n+ return None\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 = (\n+ '{\"query\": { \"bool\": { \"should\": [ '\n+ '{ \"exists\" : { \"field\" : \"url\" }} ] } } }')\n+\n+ return_fields = ['url']\n+\n+ events = self.event_stream(\n+ query_dsl=query,\n+ return_fields=return_fields,\n+ )\n+\n+ urls = {}\n+\n+ for event in events:\n+ url = self._sanitize_url(event.source.get('url'))\n+\n+ if not url:\n+ continue\n+\n+ urls.setdefault(url, []).append(event)\n+\n+ # Exit early if there are no URLs in the data set to analyze.\n+ if not urls:\n+ return 'No URLs to analyze.'\n+\n+ if not self._safebrowsing_api_key:\n+ return 'Safe Browsing API requires an API key!'\n+\n+ url_whitelisted = 0\n+\n+ url_whitelist = set(\n+ interface.get_yaml_config(\n+ self._URL_WHITELIST_CONFIG,\n+ ),\n+ )\n+\n+ if not url_whitelist:\n+ domain_analyzer_whitelisted = current_app.config.get(\n+ 'DOMAIN_ANALYZER_WHITELISTED_DOMAINS',\n+ [],\n+ )\n+ for domain in domain_analyzer_whitelisted:\n+ url_whitelist.add('*.%s/*' % domain)\n+\n+ logging.info(\n+ '{:d} entries on the whitelist.'.format(len(url_whitelist)),\n+ )\n+\n+ safebrowsing_platforms = current_app.config.get(\n+ 'SAFEBROWSING_PLATFORMS',\n+ ['ANY_PLATFORM'],\n+ )\n+\n+ safebrowsing_types = current_app.config.get(\n+ 'SAFEBROWSING_THREATTYPES',\n+ ['MALWARE'],\n+ )\n+\n+ lookup_urls = []\n+\n+ for url in urls:\n+ if self._is_url_whitelisted(url, url_whitelist):\n+ url_whitelisted += 1\n+ continue\n+\n+ lookup_urls.append(url)\n+\n+ try:\n+ safebrowsing_results = self._do_safebrowsing_lookup(\n+ lookup_urls,\n+ safebrowsing_platforms,\n+ safebrowsing_types,\n+ )\n+ except requests.HTTPError:\n+ return \"Couldn't reach the Safe Browsing API.\"\n+\n+ for url, events in urls.items():\n+ if url in safebrowsing_results:\n+ safebrowsing_result = safebrowsing_results[url]\n+ for event in events:\n+ tags = ['google-safebrowsing-url']\n+\n+ threat_type = safebrowsing_result.get('threatType')\n+\n+ if threat_type:\n+ tags.append(\n+ 'google-safebrowsing-%s' % threat_type.lower(),\n+ )\n+\n+ event.add_tags(tags)\n+ event.add_attributes(\n+ {\n+ 'google-safebrowsing-threat': safebrowsing_result,\n+ },\n+ )\n+ event.commit()\n+\n+ return '{:d} Safe Browsing result(s) on {:d} URL(s), ' \\\n+ '{:d} whitelisted.'.format(\n+ len(safebrowsing_results),\n+ len(urls),\n+ url_whitelisted,\n+ )\n+\n+\n+manager.AnalysisManager.register_analyzer(SafeBrowsingSketchPlugin)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/safebrowsing_test.py", "diff": "+\"\"\"Tests for SafeBrowsingSketchPlugin.\"\"\"\n+from __future__ import unicode_literals\n+\n+from collections import OrderedDict\n+\n+import mock\n+from httmock import HTTMock, all_requests\n+\n+from timesketch.lib.analyzers import safebrowsing\n+from timesketch.lib.testlib import BaseTest, MockDataStore\n+\n+\n+class TestSafeBrowsingSketchPlugin(BaseTest):\n+ \"\"\"Tests the functionality of the analyzer.\"\"\"\n+\n+ @mock.patch(\n+ 'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore,\n+ )\n+ def test_safebrowsing_analyzer_class(self):\n+ \"\"\"Test core functionality of the analyzer class.\"\"\"\n+ index_name = 'test'\n+ sketch_id = 1\n+ analyzer = safebrowsing.SafeBrowsingSketchPlugin(index_name, sketch_id)\n+ self.assertEqual(analyzer.index_name, index_name)\n+ self.assertEqual(analyzer.sketch.id, sketch_id)\n+\n+ @all_requests\n+ # pylint: disable=unused-argument,missing-docstring\n+ def safebrowsing_find_mock(self, url, request):\n+ MOCK_RESULT = {\n+ 'matches': [\n+ {\n+ 'threat': {\n+ 'url': 'http://A',\n+ },\n+ 'cacheDuration': '300s',\n+ 'threatEntryType': 'URL',\n+ 'threatType': 'MALWARE',\n+ 'platformType': 'ANY_PLATFORM',\n+ },\n+ {\n+ 'threat': {\n+ 'url': 'https://B',\n+ },\n+ 'cacheDuration': '300s',\n+ 'threatEntryType': 'URL',\n+ 'threatType': 'MALWARE',\n+ 'platformType': 'WINDOWS',\n+ },\n+ ],\n+ }\n+\n+ return {\n+ 'status_code': 200,\n+ 'content': MOCK_RESULT,\n+ }\n+\n+ @mock.patch(\n+ 'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore,\n+ )\n+ # pylint: disable=missing-docstring\n+ def test_do_safebrowsing_lookup(self):\n+ index_name = 'test'\n+ sketch_id = 1\n+ analyzer = safebrowsing.SafeBrowsingSketchPlugin(index_name, sketch_id)\n+\n+ with HTTMock(self.safebrowsing_find_mock):\n+ EXPECTED_RESULT = {\n+ 'http://A': {\n+ 'platformType': 'ANY_PLATFORM',\n+ 'threatType': 'MALWARE',\n+ },\n+ 'https://B': {\n+ 'platformType': 'WINDOWS',\n+ 'threatType': 'MALWARE',\n+ },\n+ }\n+\n+ # pylint: disable=protected-access\n+ actual_result = analyzer._do_safebrowsing_lookup(\n+ ['http://A', 'https://B'],\n+ [],\n+ [],\n+ )\n+\n+ self.assertEqual(\n+ OrderedDict(\n+ sorted(\n+ EXPECTED_RESULT.items(),\n+ ),\n+ ),\n+ OrderedDict(\n+ sorted(\n+ actual_result.items(),\n+ ),\n+ ),\n+ )\n+\n+ @mock.patch(\n+ 'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore,\n+ )\n+ def test_helper_functions(self):\n+ \"\"\"Tests the helper functions used by the analyzer.\"\"\"\n+ index_name = 'test'\n+ sketch_id = 1\n+ analyzer = safebrowsing.SafeBrowsingSketchPlugin(index_name, sketch_id)\n+\n+ HELPERS = [\n+ self.check_sanitize_url,\n+ self.check_whitelist,\n+ ]\n+\n+ for helper in HELPERS:\n+ helper(analyzer)\n+\n+ def check_sanitize_url(self, analyzer):\n+ URLS = [\n+ ('http://w.com', 'http://w.com'),\n+ ('https://w.com', 'https://w.com'),\n+ ('Something before@https://w.com', 'https://w.com'),\n+ ('https://w.com and after', 'https://w.com'),\n+ ('nothing', None),\n+ ]\n+\n+ for entry, result in URLS:\n+ self.assertEqual(\n+ # pylint: disable=protected-access\n+ analyzer._sanitize_url(entry),\n+ result,\n+ )\n+\n+ # pylint: disable=missing-docstring\n+ def check_whitelist(self, analyzer):\n+ WHITELIST = [\n+ 'lorem-*.com',\n+ 'ipsum.dk',\n+ 'dolo?.co.*',\n+ ]\n+\n+ self.assertTrue(\n+ # pylint: disable=protected-access\n+ analyzer._is_url_whitelisted(\n+ 'lorem-ipsum.com',\n+ WHITELIST,\n+ ),\n+ )\n+\n+ self.assertFalse(\n+ # pylint: disable=protected-access\n+ analyzer._is_url_whitelisted(\n+ 'ipsum.com',\n+ WHITELIST,\n+ ),\n+ )\n+\n+ self.assertTrue(\n+ # pylint: disable=protected-access\n+ analyzer._is_url_whitelisted(\n+ 'dolor.co.dk',\n+ WHITELIST,\n+ ),\n+ )\n+\n+ self.assertFalse(\n+ # pylint: disable=protected-access\n+ analyzer._is_url_whitelisted(\n+ 'www.amet.com',\n+ WHITELIST,\n+ ),\n+ )\n" } ]
Python
Apache License 2.0
google/timesketch
Safe Browsing analyzer
263,100
04.05.2020 12:16:44
0
f8127c955613916b05b2c90d52108e4c62b2189a
Addressing some of the issues
[ { "change_type": "MODIFY", "old_path": "data/timesketch.conf", "new_path": "data/timesketch.conf", "diff": "@@ -189,6 +189,19 @@ DOMAIN_ANALYZER_EXCLUDE_DOMAINS = ['ytimg.com', 'gstatic.com', 'yimg.com', 'akam\n# detected as 'timestomping'.\nNTFS_TIMESTOMP_ANALYZER_THRESHOLD = 10\n+# Safe Browsing API key for the URL analyzer.\n+SAFEBROWSING_API_KEY = ''\n+\n+# For the other possible values of the two settings below, please refer to\n+# the Safe Browsing API reference at:\n+# https://developers.google.com/safe-browsing/v4/reference/rest\n+\n+# Platforms to be looked at in Safe Browsing (PlatformType).\n+SAFEBROWSING_PLATFORMS = ['ANY_PLATFORM']\n+\n+# Types to be looked at in Safe Browsing (ThreatType).\n+SAFEBROWSING_THREATTYPES = ['MALWARE']\n+\n#-------------------------------------------------------------------------------\n# Enable experimental UI features.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing.py", "new_path": "timesketch/lib/analyzers/safebrowsing.py", "diff": "@@ -9,7 +9,8 @@ import pkg_resources\nimport requests\nfrom flask import current_app\n-from timesketch.lib.analyzers import interface, manager\n+from timesketch.lib.analyzers import interface\n+from timesketch.lib.analyzers import manager\nclass SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n@@ -17,15 +18,26 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nNAME = 'safebrowsing'\n+ # Safe Browsing API v4, threatMatches.find endpoint.\n+ _SAFE_BROWSING_THREATMATCHING_ENDPOINT = (\n+ 'https://safebrowsing.googleapis.com/v4/threatMatches:find')\n+\n+ # Maximal number of URLs in a single Lookup request as per the\n+ # Safe Browsing API documentation.\n_SAFE_BROWSING_BULK_LIMIT = 500\n+\n+ # An optional file containing URL wildcards to be whitelisted\n+ # in a YAML file.\n_URL_WHITELIST_CONFIG = 'safebrowsing_whitelist.yaml'\n- _SAFEBROWSING_ENTRY_KEEP = frozenset(\n- [\n+\n+ # The keys to be added to the TS event from the ThreatMatch object\n+ # we get from Safe Browsing API.\n+ _SAFEBROWSING_ENTRY_KEEP = frozenset([\n'platformType',\n'threatType',\n- ],\n- )\n+ ])\n+ # Used to find proper URLs in the 'url' entries of TS events.\n_URL_BEGINNING_RE = re.compile(r'(http(s|):\\/\\/\\S*)')\ndef __init__(self, index_name, sketch_id):\n@@ -78,13 +90,12 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n\"\"\"\nresults = {}\n- endpoint = 'https://safebrowsing.googleapis.com/v4/threatMatches:find'\napi_client = {\n'clientId': self._google_client_id,\n'clientVersion': self._google_client_version,\n}\n- for i in range(0, len(urls), self._SAFE_BROWSING_BULK_LIMIT):\n+ for index in range(0, len(urls), self._SAFE_BROWSING_BULK_LIMIT):\nbody = {\n'client': api_client,\n'threatInfo': {\n@@ -93,30 +104,42 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n'threatEntryTypes': ['URL'],\n'threatEntries': [\n{'url': url}\n- for url in urls[i:i + self._SAFE_BROWSING_BULK_LIMIT]\n+ for url in urls[\n+ index:index + self._SAFE_BROWSING_BULK_LIMIT]\n],\n},\n}\n- r = requests.post(\n- endpoint,\n+ response = requests.post(\n+ self._SAFE_BROWSING_THREATMATCHING_ENDPOINT,\nparams={'key': self._safebrowsing_api_key},\njson=body,\n)\n- r.raise_for_status()\n+ response.raise_for_status()\n- result = r.json()\n- if result and 'matches' in result:\n- for match in result['matches']:\n- threat_result = match.copy()\n+ result = response.json()\n+\n+ if not result:\n+ continue\n+\n+ if 'matches' not in result:\n+ continue\n+\n+ for match in result.get('matches'):\n+ result_url = match.get('threat', {}).get('url')\n- # Keeping only interesting keys\n+ if not result_url:\n+ continue\n+\n+ # Removing all key/values that are not defined in\n+ # the _SAFEBROWSING_ENTRY_KEEP.\n+ threat_result = match.copy()\nfor key in match.keys():\nif key not in self._SAFEBROWSING_ENTRY_KEEP:\nthreat_result.pop(key)\n- results[match['threat']['url']] = threat_result\n+ results[result_url] = threat_result\nreturn results\n@@ -127,14 +150,14 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nurl_entry: a URL, with some other characters before and after\nReturns:\n- String with the URL\n+ String with the URL or empty string if not found\n\"\"\"\nm = self._URL_BEGINNING_RE.search(url_entry)\nif m:\nreturn m.group(1)\n- return None\n+ return ''\ndef run(self):\n\"\"\"Entry point for the analyzer.\n@@ -142,6 +165,10 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nReturns:\nString with summary of the analyzer result\n\"\"\"\n+ # Exit ASAP if the API key is missing.\n+ if not self._safebrowsing_api_key:\n+ return 'Safe Browsing API requires an API key!'\n+\nquery = (\n'{\"query\": { \"bool\": { \"should\": [ '\n'{ \"exists\" : { \"field\" : \"url\" }} ] } } }')\n@@ -167,9 +194,6 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nif not urls:\nreturn 'No URLs to analyze.'\n- if not self._safebrowsing_api_key:\n- return 'Safe Browsing API requires an API key!'\n-\nurl_whitelisted = 0\nurl_whitelist = set(\n@@ -187,7 +211,7 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nurl_whitelist.add('*.%s/*' % domain)\nlogging.info(\n- '{:d} entries on the whitelist.'.format(len(url_whitelist)),\n+ '{0:d} entries on the whitelist.'.format(len(url_whitelist)),\n)\nsafebrowsing_platforms = current_app.config.get(\n@@ -216,10 +240,12 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nsafebrowsing_types,\n)\nexcept requests.HTTPError:\n- return \"Couldn't reach the Safe Browsing API.\"\n+ return 'Couldn\\'t reach the Safe Browsing API.'\nfor url, events in urls.items():\n- if url in safebrowsing_results:\n+ if url not in safebrowsing_results:\n+ continue\n+\nsafebrowsing_result = safebrowsing_results[url]\nfor event in events:\ntags = ['google-safebrowsing-url']\n@@ -239,8 +265,9 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n)\nevent.commit()\n- return '{:d} Safe Browsing result(s) on {:d} URL(s), ' \\\n- '{:d} whitelisted.'.format(\n+ return (\n+ '{0:d} Safe Browsing result(s) on {1:d} URL(s), '\n+ '{2:d} whitelisted.').format(\nlen(safebrowsing_results),\nlen(urls),\nurl_whitelisted,\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing_test.py", "new_path": "timesketch/lib/analyzers/safebrowsing_test.py", "diff": "@@ -122,7 +122,7 @@ class TestSafeBrowsingSketchPlugin(BaseTest):\n('https://w.com', 'https://w.com'),\n('Something before@https://w.com', 'https://w.com'),\n('https://w.com and after', 'https://w.com'),\n- ('nothing', None),\n+ ('nothing', ''),\n]\nfor entry, result in URLS:\n" } ]
Python
Apache License 2.0
google/timesketch
Addressing some of the issues
263,100
29.06.2020 08:27:19
0
297a07fc732c0fe4a3ef69b5cbf7daacf1c8e26c
Added python3-httmock to dpkg config
[ { "change_type": "MODIFY", "old_path": "config/dpkg/control", "new_path": "config/dpkg/control", "diff": "@@ -18,7 +18,7 @@ Description: Data files for Timesketch\nPackage: python3-timesketch\nArchitecture: all\n-Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-mans-to-es (>= 1.6), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${python3:Depends}, ${misc:Depends}\n+Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-httmock (>= 1.3.0), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-mans-to-es (>= 1.6), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${python3:Depends}, ${misc:Depends}\nDescription: Python 3 module of Timesketch\nTimesketch is a web based tool for collaborative forensic\ntimeline analysis. Using sketches you and your collaborators can easily\n" } ]
Python
Apache License 2.0
google/timesketch
Added python3-httmock to dpkg config
263,100
29.06.2020 09:45:47
0
e4703bb173599678df75fec9e4a8b50137227fe2
Fix comment - use allow list
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing.py", "new_path": "timesketch/lib/analyzers/safebrowsing.py", "diff": "@@ -26,9 +26,9 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n# Safe Browsing API documentation.\n_SAFE_BROWSING_BULK_LIMIT = 500\n- # An optional file containing URL wildcards to be whitelisted\n+ # An optional file containing URL wildcards to be allow listed\n# in a YAML file.\n- _URL_WHITELIST_CONFIG = 'safebrowsing_whitelist.yaml'\n+ _URL_ALLOW_LIST_CONFIG = 'safebrowsing_allowlist.yaml'\n# The keys to be added to the TS event from the ThreatMatch object\n# we get from Safe Browsing API.\n@@ -62,17 +62,17 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\npkg_resources.get_distribution('timesketch').version,\n)\n- def _is_url_whitelisted(self, url, whitelist):\n- \"\"\"Does a glob-match against the whitelist.\n+ def _is_url_allowlisted(self, url, allowlist):\n+ \"\"\"Does a fnmatch against the allowlist.\nArgs:\nurl: The url\n- whitelist: The whitelist, list-like\n+ allowlist: The allowlist, list-like\nReturns:\nBoolean with the result\n\"\"\"\n- for url_pattern in whitelist:\n+ for url_pattern in allowlist:\nif fnmatch.fnmatchcase(url, url_pattern):\nreturn True\n@@ -194,24 +194,24 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nif not urls:\nreturn 'No URLs to analyze.'\n- url_whitelisted = 0\n+ url_allowlisted = 0\n- url_whitelist = set(\n+ url_allowlist = set(\ninterface.get_yaml_config(\n- self._URL_WHITELIST_CONFIG,\n+ self._URL_ALLOW_LIST_CONFIG,\n),\n)\n- if not url_whitelist:\n- domain_analyzer_whitelisted = current_app.config.get(\n- 'DOMAIN_ANALYZER_WHITELISTED_DOMAINS',\n+ if not url_allowlist:\n+ domain_analyzer_allowlisted = current_app.config.get(\n+ 'DOMAIN_ANALYZER_EXCLUDE_DOMAINS',\n[],\n)\n- for domain in domain_analyzer_whitelisted:\n- url_whitelist.add('*.%s/*' % domain)\n+ for domain in domain_analyzer_allowlisted:\n+ url_allowlist.add('*.%s/*' % domain)\nlogging.info(\n- '{0:d} entries on the whitelist.'.format(len(url_whitelist)),\n+ '{0:d} entries on the allowlist.'.format(len(url_allowlist)),\n)\nsafebrowsing_platforms = current_app.config.get(\n@@ -227,8 +227,8 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nlookup_urls = []\nfor url in urls:\n- if self._is_url_whitelisted(url, url_whitelist):\n- url_whitelisted += 1\n+ if self._is_url_allowlisted(url, url_allowlist):\n+ url_allowlisted += 1\ncontinue\nlookup_urls.append(url)\n@@ -267,10 +267,10 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nreturn (\n'{0:d} Safe Browsing result(s) on {1:d} URL(s), '\n- '{2:d} whitelisted.').format(\n+ '{2:d} allow listed.').format(\nlen(safebrowsing_results),\nlen(urls),\n- url_whitelisted,\n+ url_allowlisted,\n)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing_test.py", "new_path": "timesketch/lib/analyzers/safebrowsing_test.py", "diff": "@@ -110,7 +110,7 @@ class TestSafeBrowsingSketchPlugin(BaseTest):\nHELPERS = [\nself.check_sanitize_url,\n- self.check_whitelist,\n+ self.check_allowlist,\n]\nfor helper in HELPERS:\n@@ -133,8 +133,8 @@ class TestSafeBrowsingSketchPlugin(BaseTest):\n)\n# pylint: disable=missing-docstring\n- def check_whitelist(self, analyzer):\n- WHITELIST = [\n+ def check_allowlist(self, analyzer):\n+ ALLOW_LIST = [\n'lorem-*.com',\n'ipsum.dk',\n'dolo?.co.*',\n@@ -142,32 +142,32 @@ class TestSafeBrowsingSketchPlugin(BaseTest):\nself.assertTrue(\n# pylint: disable=protected-access\n- analyzer._is_url_whitelisted(\n+ analyzer._is_url_allowlisted(\n'lorem-ipsum.com',\n- WHITELIST,\n+ ALLOW_LIST,\n),\n)\nself.assertFalse(\n# pylint: disable=protected-access\n- analyzer._is_url_whitelisted(\n+ analyzer._is_url_allowlisted(\n'ipsum.com',\n- WHITELIST,\n+ ALLOW_LIST,\n),\n)\nself.assertTrue(\n# pylint: disable=protected-access\n- analyzer._is_url_whitelisted(\n+ analyzer._is_url_allowlisted(\n'dolor.co.dk',\n- WHITELIST,\n+ ALLOW_LIST,\n),\n)\nself.assertFalse(\n# pylint: disable=protected-access\n- analyzer._is_url_whitelisted(\n+ analyzer._is_url_allowlisted(\n'www.amet.com',\n- WHITELIST,\n+ ALLOW_LIST,\n),\n)\n" } ]
Python
Apache License 2.0
google/timesketch
Fix comment - use allow list
263,100
29.06.2020 10:00:23
0
e0bc11762242217ec80ece178b9181585e8067b6
Key-value string with the attributes
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing.py", "new_path": "timesketch/lib/analyzers/safebrowsing.py", "diff": "@@ -258,9 +258,15 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\n)\nevent.add_tags(tags)\n+\n+ threat_attributes = []\n+ for item in safebrowsing_result.items():\n+ threat_attributes.append('%s: %s' % item)\n+\nevent.add_attributes(\n{\n- 'google-safebrowsing-threat': safebrowsing_result,\n+ 'google-safebrowsing-threat': ', '.join(\n+ threat_attributes),\n},\n)\nevent.commit()\n" } ]
Python
Apache License 2.0
google/timesketch
Key-value string with the attributes
263,100
29.06.2020 10:11:33
0
ff8ebe9a172cd1307b0a398c639f7ab7a56d9f48
Logging HTTP errors
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing.py", "new_path": "timesketch/lib/analyzers/safebrowsing.py", "diff": "@@ -116,7 +116,11 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\njson=body,\n)\n+ try:\nresponse.raise_for_status()\n+ except requests.exceptions.HTTPError as e:\n+ logging.error(e)\n+ continue\nresult = response.json()\n" } ]
Python
Apache License 2.0
google/timesketch
Logging HTTP errors
263,100
29.06.2020 10:11:56
0
7ebd6a0e08d8d09f563b3163c15c7fd068fc7847
Only the actual URLs need to be looked at here
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/safebrowsing.py", "new_path": "timesketch/lib/analyzers/safebrowsing.py", "diff": "@@ -246,12 +246,12 @@ class SafeBrowsingSketchPlugin(interface.BaseSketchAnalyzer):\nexcept requests.HTTPError:\nreturn 'Couldn\\'t reach the Safe Browsing API.'\n- for url, events in urls.items():\n+ for url in lookup_urls:\nif url not in safebrowsing_results:\ncontinue\nsafebrowsing_result = safebrowsing_results[url]\n- for event in events:\n+ for event in urls[url]:\ntags = ['google-safebrowsing-url']\nthreat_type = safebrowsing_result.get('threatType')\n" } ]
Python
Apache License 2.0
google/timesketch
Only the actual URLs need to be looked at here
263,096
08.07.2020 15:20:34
-7,200
1a365d79f73fac1a7e331efc3c78bc2354e0184d
[Docker-doc] How to run tests How to run the timesketch tests in docker.
[ { "change_type": "MODIFY", "old_path": "docker/dev/README.md", "new_path": "docker/dev/README.md", "diff": "@@ -44,3 +44,10 @@ sudo docker exec -it $CONTAINER_ID gunicorn --reload -b 0.0.0.0:5000 --log-file\nYou now can access your development version at http://127.0.0.1:5000/\nLog in with user: dev password: dev\n+### Run tests\n+\n+```\n+docker exec -w /usr/local/src/timesketch -it $CONTAINER_ID python3 run_tests.py --coverage\n+```\n+\n+That will run all tests in your docker container. It is recommended to run all tests at least before creating a pull request.\n" } ]
Python
Apache License 2.0
google/timesketch
[Docker-doc] How to run tests (#1289) How to run the timesketch tests in docker.
263,178
09.07.2020 13:01:07
-7,200
25257915496e4b60593f2285817b5f8f95495316
Moved pylint CI checks to run in tox
[ { "change_type": "MODIFY", "old_path": ".pylintrc", "new_path": ".pylintrc", "diff": "@@ -67,6 +67,7 @@ confidence=\n# --disable=W\".\ndisable=assignment-from-none,\nbad-inline-option,\n+ cyclic-import,\ndeprecated-pragma,\nduplicate-code,\neq-without-hash,\n" }, { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -19,35 +19,54 @@ jobs:\nservices:\n- docker\n- name: \"Ubuntu Bionic (18.04) (Docker) with Python 3.6 using PyPI\"\n- env: [TARGET=\"pypi\", UBUNTU_VERSION=\"18.04\"]\n+ env:\n+ - TARGET=\"pypi\"\n+ - UBUNTU_VERSION=\"18.04\"\ngroup: edge\nlanguage: python\npython: 3.6\nservices:\n- docker\n- name: \"Ubuntu Focal (20.04) (Docker) with Python 3.8 using PyPI\"\n- env: [TARGET=\"pypi\", UBUNTU_VERSION=\"20.04\"]\n+ env:\n+ - TARGET=\"pypi\"\n+ - UBUNTU_VERSION=\"20.04\"\ngroup: edge\nlanguage: python\npython: 3.8\nservices:\n- docker\n- name: \"Ubuntu Focal (20.04) (Docker) with Python 3.6 (tox)\"\n- env: [TOXENV=\"py36\", UBUNTU_VERSION=\"20.04\"]\n+ env:\n+ - TOXENV=\"py36\"\n+ - UBUNTU_VERSION=\"20.04\"\ngroup: edge\nlanguage: python\npython: 3.6\nservices:\n- docker\n- name: \"Ubuntu Focal (20.04) (Docker) with Python 3.7 (tox)\"\n- env: [TOXENV=\"py37\", UBUNTU_VERSION=\"20.04\"]\n+ env:\n+ - TOXENV=\"py37\"\n+ - UBUNTU_VERSION=\"20.04\"\ngroup: edge\nlanguage: python\npython: 3.7\nservices:\n- docker\n- name: \"Ubuntu Focal (20.04) (Docker) with Python 3.8 (tox)\"\n- env: [TOXENV=\"py38\", UBUNTU_VERSION=\"20.04\"]\n+ env:\n+ - TOXENV=\"py38\"\n+ - UBUNTU_VERSION=\"20.04\"\n+ group: edge\n+ language: python\n+ python: 3.8\n+ services:\n+ - docker\n+ - name: \"Pylint on Ubuntu Focal (20.04) (Docker) with Python 3.8 (tox)\"\n+ env:\n+ - TOXENV=\"pylint\"\n+ - UBUNTU_VERSION=\"20.04\"\ngroup: edge\nlanguage: python\npython: 3.8\n" }, { "change_type": "MODIFY", "old_path": "run_tests.py", "new_path": "run_tests.py", "diff": "@@ -27,9 +27,6 @@ def run_python(args):\nif not args.no_tests:\nrun_python_tests(coverage=args.coverage)\n- if not args.no_lint:\n- subprocess.check_call(['./config/travis/run_pylint.sh', '--coverage'])\n-\ndef parse_cli_args(args=None):\n\"\"\"Parse command-line arguments to this script.\n@@ -39,7 +36,7 @@ def parse_cli_args(args=None):\nReturns:\nInstance of argparse.Namespace with the following boolean attributes:\n- py, js, selenium, full, no_lint, no_tests, coverage\n+ py, js, selenium, full, no_tests, coverage\nRaises:\nSystemExit if arguments are invalid or --help is present.\n@@ -47,10 +44,6 @@ def parse_cli_args(args=None):\np = argparse.ArgumentParser(\ndescription=\"Run Python unit tests and linters.\"\n)\n- p.add_argument(\n- '--no-lint', action='store_true',\n- help='Skip all linters.'\n- )\np.add_argument(\n'--no-tests', action='store_true',\nhelp='Skip tests, run only linters.'\n" }, { "change_type": "MODIFY", "old_path": "test_requirements.txt", "new_path": "test_requirements.txt", "diff": "@@ -4,4 +4,3 @@ nose >= 1.3.7\npbr >= 4.2.0\nbeautifulsoup4 >= 4.8.2\ncoverage >= 5.0.2\n-pylint >= 2.4.0, < 2.5.0\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/phishy_domains.py", "new_path": "timesketch/lib/analyzers/phishy_domains.py", "diff": "@@ -49,8 +49,9 @@ class PhishyDomainsSketchPlugin(interface.BaseSketchAnalyzer):\n# TODO: remove that after a 6 months, this following check is to ensure\n# compatibility of the config file.\nif len(self.domain_scoring_exclude_domains) == 0:\n- logging.warning('Warning, DOMAIN_ANALYZER_WHITELISTED_DOMAINS has been deprecated. '\n- 'Please update timesketch.conf.')\n+ logging.warning(\n+ 'Warning, DOMAIN_ANALYZER_WHITELISTED_DOMAINS has been '\n+ 'deprecated. Please update timesketch.conf.')\nself.domain_scoring_exclude_domains = current_app.config.get(\n'DOMAIN_ANALYZER_WHITELISTED_DOMAINS', [])\n@@ -217,7 +218,8 @@ class PhishyDomainsSketchPlugin(interface.BaseSketchAnalyzer):\nfor domain in watched_domains_list_temp:\nif domain in self.domain_scoring_exclude_domains:\ncontinue\n- if any(domain.endswith(x) for x in self.domain_scoring_exclude_domains):\n+ if any(domain.endswith(x)\n+ for x in self.domain_scoring_exclude_domains):\ncontinue\nif '.' not in domain:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/sigma_tagger.py", "new_path": "timesketch/lib/analyzers/sigma_tagger.py", "diff": "@@ -89,9 +89,9 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\n# if a sub dir is found, append it to be scanned for rules\nif os.path.isdir(os.path.join(rules_path, rule_filename)):\n- logging.error(\n- 'this is a directory, not a file, skipping: {0:s}'.format(\n- rule_filename))\n+ logging.error((\n+ 'this is a directory, not a file, skipping: '\n+ '{0:s}').format(rule_filename))\ncontinue\ntag_name, _ = rule_filename.rsplit('.')\n@@ -107,32 +107,40 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nrule_file_content, self.sigma_config, None)\nparsed_sigma_rules = parser.generate(sigma_backend)\nexcept NotImplementedError as exception:\n- logging.error(\n- 'Error generating rule in file {0:s}: {1!s}'.format(\n- rule_file_path, exception))\n+ logging.error((\n+ 'Error generating rule in file {0:s}: '\n+ '{1!s}').format(rule_file_path, exception))\ncontinue\n- except Exception as exception:\n- logging.error(\n- 'Error generating rule in file {0:s}: {1!s}'.format(\n- rule_file_path, exception))\n+ except Exception as exception: # pylint: disable=broad-except\n+ logging.error((\n+ 'Error generating rule in file {0:s}: '\n+ '{1!s}').format(rule_file_path, exception))\ncontinue\nfor sigma_rule in parsed_sigma_rules:\ntry:\nsimple_counter += 1\n- # TODO fix that in Sigma hack to get rid of nested stuff\n+ # TODO fix that in Sigma hack to get rid of\n+ # nested stuff. Also see:\n# https://github.com/google/timesketch/issues/1199#issuecomment-639475885\n- sigma_rule = sigma_rule.replace(\".keyword:\", \":\")\n+ sigma_rule = sigma_rule.replace(\n+ \".keyword:\", \":\")\nlogging.info(\n- '[sigma] Generated query {0:s}'.format(sigma_rule))\n+ '[sigma] Generated query {0:s}'.format(\n+ sigma_rule))\nnumber_of_tagged_events = self.run_sigma_rule(\nsigma_rule, tag_name)\n- tags_applied[tag_name] += number_of_tagged_events\n- except elasticsearch.TransportError as es_TransportError:\n- logging.error(\n- 'Timeout generating rule in file {0:s}: {1!s} waiting for 10 seconds'.format(\n- rule_file_path, es_TransportError))\n- time.sleep(10) # waiting 5 seconds before continue\n+ tags_applied[tag_name] += (\n+ number_of_tagged_events)\n+\n+ except elasticsearch.TransportError as exception:\n+ logging.error((\n+ 'Timeout generating rule in file {0:s}: '\n+ '{1!s} waiting for 10 seconds').format(\n+ rule_file_path, exception))\n+\n+ # Waiting 10 seconds before continuing.\n+ time.sleep(10)\ntotal_tagged_events = sum(tags_applied.values())\noutput_string = 'Applied {0:d} tags\\n'.format(total_tagged_events)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/datastores/elastic.py", "new_path": "timesketch/lib/datastores/elastic.py", "diff": "@@ -651,7 +651,7 @@ class ElasticsearchDataStore(object):\nif self.import_events:\ntry:\nself.client.bulk(body=self.import_events)\n- except (ConnectionTimeout, socket.timeout) as e:\n+ except (ConnectionTimeout, socket.timeout):\n# TODO: Add a retry here.\nes_logger.error('Unable to add events', exc_info=True)\n" }, { "change_type": "MODIFY", "old_path": "tox.ini", "new_path": "tox.ini", "diff": "@@ -27,7 +27,6 @@ deps =\nCython\n-rrequirements.txt\n-rtest_requirements.txt\n- # TODO: remove pylint from test_requirements.txt and run_tests.py\n- # pylint >= 2.4.0, < 2.5.0\n+ pylint >= 2.4.0, < 2.5.0\ncommands =\n- pylint --rcfile=.pylintrc api_client/python/timesketch_api_client importer_client/python/timesketch_import_client timesketch tests\n+ pylint --rcfile=.pylintrc api_client/python/timesketch_api_client importer_client/python/timesketch_import_client timesketch\n" } ]
Python
Apache License 2.0
google/timesketch
Moved pylint CI checks to run in tox (#1266)
263,178
09.07.2020 13:09:48
-7,200
e7b933abc72d556f1b257055640aa3488d390c41
Added update release script and updated versions
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/version.py", "new_path": "api_client/python/timesketch_api_client/version.py", "diff": "# limitations under the License.\n\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20200707'\n+__version__ = '20200709'\ndef get_version():\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/changelog", "new_path": "config/dpkg/changelog", "diff": "-timesketch (20200525-1) unstable; urgency=low\n+timesketch (20200709-1) unstable; urgency=low\n* Auto-generated\n- -- Timesketch development team <timesketch-dev@googlegroups.com> Mon, 25 May 2020 13:41:01 +0200\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> Thu, 09 Jul 2020 12:41:29 +0200\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/version.py", "new_path": "importer_client/python/timesketch_import_client/version.py", "diff": "# limitations under the License.\n\"\"\"Version information for Timesketch Import Client.\"\"\"\n-__version__ = '20200707'\n+__version__ = '20200709'\ndef get_version():\n" }, { "change_type": "MODIFY", "old_path": "timesketch/version.py", "new_path": "timesketch/version.py", "diff": "# limitations under the License.\n\"\"\"Version information for Timesketch.\"\"\"\n-__version__ = '20200507'\n+__version__ = '20200709'\ndef get_version():\n" }, { "change_type": "ADD", "old_path": null, "new_path": "utils/update_release.sh", "diff": "+#!/bin/bash\n+#\n+# Script that makes changes in preparation of a new release, such as updating\n+# the version and documentation.\n+\n+EXIT_FAILURE=1;\n+EXIT_SUCCESS=0;\n+\n+VERSION=`date -u +\"%Y%m%d\"`\n+DPKG_DATE=`date -R`\n+\n+# Update the Python module versions.\n+sed \"s/__version__ = '[0-9]*'/__version__ = '${VERSION}'/\" -i api_client/python/timesketch_api_client/version.py\n+sed \"s/__version__ = '[0-9]*'/__version__ = '${VERSION}'/\" -i importer_client/python/timesketch_import_client/version.py\n+sed \"s/__version__ = '[0-9]*'/__version__ = '${VERSION}'/\" -i timesketch/version.py\n+\n+# Update the version in the dpkg configuration files.\n+cat > config/dpkg/changelog << EOT\n+timesketch (${VERSION}-1) unstable; urgency=low\n+\n+ * Auto-generated\n+\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> ${DPKG_DATE}\n+EOT\n+\n+# Regenerate the API documentation.\n+# TODO: implement\n+# tox -edocs\n+\n+exit ${EXIT_SUCCESS};\n+\n" } ]
Python
Apache License 2.0
google/timesketch
Added update release script and updated versions (#1293) Co-authored-by: Johan Berggren <jberggren@gmail.com>
263,133
09.07.2020 13:21:48
0
d15ffb2b7f9f1c44d69832f29ef54b9d4508b4eb
Updating test tools to reflect changes to interface, changing a bit error handling as well.
[ { "change_type": "ADD", "old_path": "test_tools/etc/timesketch/__init__.py", "new_path": "test_tools/etc/timesketch/__init__.py", "diff": "" }, { "change_type": "MODIFY", "old_path": "test_tools/timesketch/lib/analyzers/interface.py", "new_path": "test_tools/timesketch/lib/analyzers/interface.py", "diff": "@@ -18,6 +18,7 @@ import codecs\nimport collections\nimport csv\nimport json\n+import logging\nimport os\nimport traceback\nimport uuid\n@@ -27,6 +28,9 @@ import pandas\nfrom timesketch.lib import definitions\n+logger = logging.getLogger('test_tool.analyzer_run')\n+\n+\n# Define named tuples to track changes made to events and sketches.\nEVENT_CHANGE = collections.namedtuple('event_change', 'type, source, what')\nSKETCH_CHANGE = collections.namedtuple('sketch_change', 'type, source, what')\n@@ -35,6 +39,32 @@ VIEW_OBJECT = collections.namedtuple('view', 'id, name')\nAGG_OBJECT = collections.namedtuple('aggregation', 'id, name parameters')\n+def get_config_path(file_name):\n+ \"\"\"Returns a path to a configuration file.\n+\n+ Args:\n+ file_name: String that defines the config file name.\n+\n+ Returns:\n+ The path to the configuration file or None if the file cannot be found.\n+ \"\"\"\n+ path = os.path.join('etc', 'timesketch', file_name)\n+ if os.path.isfile(path):\n+ return os.path.abspath(path)\n+\n+ path = os.path.join('data', file_name)\n+ if os.path.isfile(path):\n+ return os.path.abspath(path)\n+\n+ path = os.path.join(\n+ os.path.dirname(__file__), '..', 'data', file_name)\n+ path = os.path.abspath(path)\n+ if os.path.isfile(path):\n+ return path\n+\n+ return None\n+\n+\nclass AnalyzerContext(object):\n\"\"\"Report object for analyzer run.\"\"\"\n@@ -44,6 +74,7 @@ class AnalyzerContext(object):\nself.analyzer_result = ''\nself.error = None\nself.event_cache = {}\n+ self.failed = False\nself.sketch = None\nself.queries = []\n@@ -65,6 +96,9 @@ class AnalyzerContext(object):\nfor key, value in query.items():\nreturn_strings.append('{0:>20s}: {1!s}'.format(key, value))\n+ if self.failed:\n+ return '\\n'.join(return_strings)\n+\nif self.sketch and self.sketch.updates:\nreturn_strings.append('')\nreturn_strings.append('+'*80)\n@@ -562,15 +596,34 @@ class BaseIndexAnalyzer(object):\nquery_string=query_string, query_dsl=query_dsl,\nindices=indices, fields=return_fields)\n+ _, _, file_extension = self._file_name.rpartition('.')\n+ file_extension = file_extension.lower()\n+ if file_extension not in ['csv', 'jsonl']:\n+ raise ValueError(\n+ 'Unable to parse the test file [{0:s}] unless it has the '\n+ 'extension of either .csv or .jsonl'.format(self._file_name))\n+\nwith codecs.open(\n- self._file_name, encoding='utf-8', errors='replace') as csv_fh:\n- reader = csv.DictReader(csv_fh)\n+ self._file_name, encoding='utf-8', errors='replace') as fh:\n+\n+ if file_extension == 'csv':\n+ reader = csv.DictReader(fh)\nfor row in reader:\n- event = Event(row, sketch=self.sketch, context=self._context)\n+ event = Event(\n+ row, sketch=self.sketch, context=self._context)\n+ if self._context:\n+ self._context.add_event(event)\n+ yield event\n+ elif file_extension == 'jsonl':\n+ for row in fh:\n+ event = Event(\n+ json.loads(row), sketch=self.sketch,\n+ context=self._context)\nif self._context:\nself._context.add_event(event)\nyield event\n+\ndef run_wrapper(self):\n\"\"\"A wrapper method to run the analyzer.\n@@ -584,6 +637,11 @@ class BaseIndexAnalyzer(object):\nexcept Exception: # pylint: disable=broad-except\nif self._context:\nself._context.error = traceback.format_exc()\n+ logger.error(\n+ 'Unable to run the analyzer.\\nMake sure the test data '\n+ 'contains all the necessary information to run.'\n+ '\\n\\nThe traceback for the execution is:\\n\\n', exc_info=True)\n+ self._context.failed = True\nreturn\n# Update database analysis object with result and status\n@@ -726,6 +784,23 @@ class Story(object):\nchange = SKETCH_CHANGE('STORY_ADD', 'aggregation', params)\nself._analyzer.updates.append(change)\n+ def add_aggregation_group(self, aggregation_group):\n+ \"\"\"Add an aggregation group to the Story.\n+\n+ Args:\n+ aggregation_group (SQLAggregationGroup): Save aggregation group\n+ to add to the story.\n+ \"\"\"\n+ if not isinstance(aggregation_group, AggregationGroup):\n+ return\n+\n+ params = {\n+ 'group_id': aggregation_group.id,\n+ 'group_name': aggregation_group.name\n+ }\n+ change = SKETCH_CHANGE('STORY_ADD', 'aggregation_group', params)\n+ self._analyzer.updates.append(change)\n+\ndef add_text(self, text, skip_if_exists=False):\n\"\"\"Add a text block to the Story.\n" } ]
Python
Apache License 2.0
google/timesketch
Updating test tools to reflect changes to interface, changing a bit error handling as well. (#1296)
263,093
09.07.2020 16:05:04
-7,200
bd4d50b2737e5ed8c8e379618d64be97f0deaebc
Update update_release.sh
[ { "change_type": "MODIFY", "old_path": "utils/update_release.sh", "new_path": "utils/update_release.sh", "diff": "@@ -10,8 +10,6 @@ VERSION=`date -u +\"%Y%m%d\"`\nDPKG_DATE=`date -R`\n# Update the Python module versions.\n-sed \"s/__version__ = '[0-9]*'/__version__ = '${VERSION}'/\" -i api_client/python/timesketch_api_client/version.py\n-sed \"s/__version__ = '[0-9]*'/__version__ = '${VERSION}'/\" -i importer_client/python/timesketch_import_client/version.py\nsed \"s/__version__ = '[0-9]*'/__version__ = '${VERSION}'/\" -i timesketch/version.py\n# Update the version in the dpkg configuration files.\n" } ]
Python
Apache License 2.0
google/timesketch
Update update_release.sh (#1297)
263,133
11.07.2020 20:39:42
0
e8c64343fd21e8adb2f6f531995f9756d8b8f9d0
Minor updates to the upload data doc.
[ { "change_type": "MODIFY", "old_path": "docs/UploadData.md", "new_path": "docs/UploadData.md", "diff": "@@ -16,14 +16,15 @@ Let's explore each of these ways a bit further.\n## Using the importer CLI Tool.\nIf the data that is to be imported is a single file then the importer tool\n-can be used. It utilizes the importer library and the API client to upload\n-the file. This is a simple wrapper around the importer library. The tool comes\n+can be used. It utilizes the importer client library and the API client to upload\n+the file. This is a simple wrapper around the importer client libraries. The tool comes\nwith the installation of the timesketch importer client.\nThere are two methods to use the tool:\n1. Define all parameters on the command line.\n-2. Define the parameters in the [~/.timesketchrc](/docs/APIConfigFile.md) file.\n+2. The preferred method of just running the tool omitting all information about the\n+authentication and/or server information and have the tool ask all the questions.\nThe easiest way to discover the parameters and how to run the tool is to run:\n@@ -37,12 +38,12 @@ The minimum set of parameters to the run tool are:\n$ timesketch_importer.py path_to_my_file.csv\n```\n-However this requires that the `~/.timesketchrc` file contains all the necessary\n-configs. If there are configuration items that are missing then the tool will\n-ask questions to get the remaining parameters.\n+If the information to connect to Timesketch are not present (host information,\n+auth method and auth information) then the tool will ask the user for the missing\n+information and store it in the configuration file `~/.timesketchrc` for future use.\nRemember for OAUTH authentication both `client_id` and `client_secret` need to\n-be set.\n+provided to the tool.\nThe tool will store the user credentials in an encrypted file as soon as it\nruns for the first time. This token file will be used for subsequent uses\n" } ]
Python
Apache License 2.0
google/timesketch
Minor updates to the upload data doc.
263,178
13.07.2020 10:40:31
-7,200
2d3d0b994a14148141ec17e242f07358bea8a1a3
Updated dpkg files
[ { "change_type": "MODIFY", "old_path": "config/dpkg/changelog", "new_path": "config/dpkg/changelog", "diff": "-timesketch (20200709-1) unstable; urgency=low\n+timesketch (20200710-1) unstable; urgency=low\n* Auto-generated\n- -- Timesketch development team <timesketch-dev@googlegroups.com> Thu, 09 Jul 2020 12:41:29 +0200\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> Fri, 10 Jul 2020 18:16:13 +0200\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/control", "new_path": "config/dpkg/control", "diff": "@@ -18,7 +18,7 @@ Description: Data files for Timesketch\nPackage: python3-timesketch\nArchitecture: all\n-Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-httmock (>= 1.3.0), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-mans-to-es (>= 1.6), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${python3:Depends}, ${misc:Depends}\n+Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 1.3.2), python3-altair (>= 4.1.0), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.4.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.5.0), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 7.5.1), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.1.1), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.1), python3-flask-migrate (>= 2.5.2), python3-flask-restful (>= 0.3.7), python3-flask-script (>= 2.0.6), python3-flask-sqlalchemy (>= 2.4.1), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.7.0), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.7.1), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.17.5), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.25.3), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 3.3.11), python3-requests (>= 2.23.0), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.3.12), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${python3:Depends}, ${misc:Depends}\nDescription: Python 3 module of Timesketch\nTimesketch is a web based tool for collaborative forensic\ntimeline analysis. Using sketches you and your collaborators can easily\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/python3-timesketch.install", "new_path": "config/dpkg/python3-timesketch.install", "diff": "@@ -4,8 +4,4 @@ usr/lib/python3*/dist-packages/timesketch/*/*/*.py\nusr/lib/python3*/dist-packages/timesketch/*/*/*/*.py\nusr/lib/python3*/dist-packages/timesketch/frontend/dist/*\nusr/lib/python3*/dist-packages/timesketch/frontend/dist/*/*\n-usr/lib/python3*/dist-packages/timesketch/static/*/*\n-usr/lib/python3*/dist-packages/timesketch/static/*/*/*\n-usr/lib/python3*/dist-packages/timesketch/templates/*\n-usr/lib/python3*/dist-packages/timesketch/templates/*/*\nusr/lib/python3*/dist-packages/timesketch*.egg-info/*\n" }, { "change_type": "MODIFY", "old_path": "dependencies.ini", "new_path": "dependencies.ini", "diff": "@@ -162,7 +162,7 @@ rpm_name: python3-google-auth-oauthlib\n[gunicorn]\ndpkg_name: python3-gunicorn\n-minimum_version: 19.10.0\n+minimum_version: 19.7.1\nrpm_name: python3-gunicorn\n[idna]\n@@ -237,7 +237,7 @@ rpm_name: python3-pycparser\n[PyJWT]\ndpkg_name: python3-jwt\n-minimum_version: 5.3\n+minimum_version: 1.7.1\nrpm_name: python3-jwt\n[pyrsistent]\n" } ]
Python
Apache License 2.0
google/timesketch
Updated dpkg files (#1302)
263,133
14.07.2020 13:43:01
0
d1f681dcfd5f64fca6f3f64633a0e3f7677bc6b3
Minor changes to test tools
[ { "change_type": "MODIFY", "old_path": "test_tools/timesketch/lib/analyzers/interface.py", "new_path": "test_tools/timesketch/lib/analyzers/interface.py", "diff": "@@ -46,7 +46,8 @@ def get_config_path(file_name):\nfile_name: String that defines the config file name.\nReturns:\n- The path to the configuration file or None if the file cannot be found.\n+ The path to the configuration file or an empty string if the file\n+ cannot be found.\n\"\"\"\npath = os.path.join('etc', 'timesketch', file_name)\nif os.path.isfile(path):\n@@ -62,7 +63,13 @@ def get_config_path(file_name):\nif os.path.isfile(path):\nreturn path\n- return None\n+ path = os.path.join(\n+ os.path.dirname(__file__), '..', '..', '..', '..', 'data', file_name)\n+ path = os.path.abspath(path)\n+ if os.path.isfile(path):\n+ return path\n+\n+ return ''\nclass AnalyzerContext(object):\n" }, { "change_type": "MODIFY", "old_path": "test_tools/timesketch/lib/analyzers/utils.py", "new_path": "test_tools/timesketch/lib/analyzers/utils.py", "diff": "@@ -29,6 +29,14 @@ based analyzers contribute to. Each section in this story\nis generated by a separate analyzer.\n\"\"\"\n+# Title and header text of a story that is common among browser\n+# based analyzers.\n+SIGMA_STORY_TITLE = 'Sigma Artifacts'\n+SIGMA_STORY_HEADER = \"\"\"\n+This is an automatically generated story that Sigma\n+based analyzers contribute to.\n+\"\"\"\n+\n# CDN domain list based on:\n# https://github.com/WPO-Foundation/webpagetest/blob/master/agent/wpthook/cdn.h\n# Last updated: 2019-01-11\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to test tools
263,095
15.07.2020 14:37:44
-7,200
3ab1fc53c08daa3e4c31d9457f0b18e926d5e8ba
Verify Sigma Rules test tool
[ { "change_type": "MODIFY", "old_path": "docs/UseSigmaAnalyzer.md", "new_path": "docs/UseSigmaAnalyzer.md", "diff": "@@ -83,3 +83,37 @@ If you want to test that feature, get some evtx files from the following\n- https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES\n- https://github.com/sans-blue-team/DeepBlueCLI/evtx\n+\n+## Verify rules\n+\n+Deploying rules that can not be parsed by Sigma can cause problems on analyst side\n+as well as Timesketch operator side. The analyst might not be able to see\n+the logs and the errors might only occur when running the analyzer.\n+\n+This is why a standalone tool can be used from:\n+```\n+test_tools/sigma_verify_rules.py\n+```\n+\n+This tool takes the following options:\n+```\n+usage: sigma_verify_rules.py [-h] [--config_file PATH_TO_TEST_FILE]\n+ PATH_TO_RULES\n+sigma_verify_rules.py: error: the following arguments are required: PATH_TO_RULES\n+```\n+\n+And could be used like the following to verify your rules would work:\n+```\n+sigma_verfy_rules.py --config_file sigma_config.yaml ../timesketch/data/sigma/rules\n+```\n+\n+If any rules in that folder is causing problems it will be shown:\n+```\n+sigma_verify_rules.py --config_file ../data/sigma_config.yaml ../timesketch/data/sigma/rules\n+ERROR:root:reverse_shell.yaml Error generating rule in file ../timesketch/data/sigma/rules/linux/reverse_shell.yaml you should not use this rule in Timesketch: No condition found\n+ERROR:root:recon_commands.yaml Error generating rule in file ../timesketch/data/sigma/rules/data/linux/recon_commands.yaml you should not use this rule in Timesketch: No condition found\n+You should NOT import the following rules\n+../timesketch/data/sigma/rules/linux/reverse_shell.yaml\n+../timesketch/data/sigma/rules/linux/recon_commands.yaml\n+```\n+\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test_tools/sigma_verify_rules.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"A tool to test sigma rules.\n+This tool can be used to verify your rules before running an analyzer.\n+It also does not require you to have a full blown Timesketch instance up and running.\n+Example way of running the tool:\n+ $ sigma_verify_rules.py --config_file ../data/sigma_config.yaml ../data/linux/\n+\"\"\"\n+\n+\n+import logging\n+import os\n+import argparse\n+import sys\n+\n+\n+\n+from sigma.backends import elasticsearch as sigma_elasticsearch\n+import sigma.configuration as sigma_configuration\n+from sigma.parser import collection as sigma_collection\n+logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"ERROR\"))\n+import sigma.parser.exceptions\n+\n+\n+def get_codepath():\n+ \"\"\"Return the absolute path to where the tool is run from.\"\"\"\n+ path = __file__\n+ if path.startswith(os.path.sep):\n+ return path\n+\n+ dirname = os.path.dirname(path)\n+ for sys_path in sys.path:\n+ if sys_path.endswith(dirname):\n+ return sys_path\n+ return dirname\n+\n+\n+def run_verifier(rules_path, config_file_path):\n+ \"\"\"Run an sigma parsing test on a given dir and returns results from the run.\n+ Args:\n+ rules_path: the path to the rules.\n+ config_file_path: the path to a config file that contains mapping data.\n+ Raises:\n+ IOError: if the path to either test or analyzer file does not exist\n+ or if the analyzer module or class cannot be loaded.\n+ Returns:\n+ two lists:\n+ - sigma_verified_rules with rules that can be added\n+ - sigma_rules_with_problems with rules that should not be added\n+ \"\"\"\n+ if not os.path.isdir(rules_path):\n+ raise IOError('Rules not found at path: {0:s}'.format(\n+ rules_path))\n+ if not os.path.isfile(config_file_path):\n+ raise IOError('Config file path not found at path: {0:s}'.format(\n+ config_file_path))\n+\n+ sigma_config_path = config_file_path\n+\n+ with open(sigma_config_path, 'r') as sigma_config_file:\n+ sigma_config_con = sigma_config_file.read()\n+ sigma_config = sigma_configuration.SigmaConfiguration(sigma_config_con)\n+ sigma_backend = sigma_elasticsearch.ElasticsearchQuerystringBackend(sigma_config, {})\n+\n+ for dirpath, dirnames, files in os.walk(rules_path):\n+\n+ if 'deprecated' in dirnames:\n+ dirnames.remove('deprecated')\n+\n+ rule_extensions = (\"yml\",\"yaml\")\n+\n+ sigma_verified_rules = []\n+ sigma_rules_with_problems = []\n+\n+ for rule_filename in files:\n+ if rule_filename.lower().endswith(rule_extensions):\n+\n+ # if a sub dir is found, append it to be scanned for rules\n+ if os.path.isdir(os.path.join(rules_path, rule_filename)):\n+ logging.error(\n+ 'this is a directory, skipping: {0:s}'.format(\n+ rule_filename))\n+ continue\n+\n+ tag_name, _ = rule_filename.rsplit('.')\n+ rule_file_path = os.path.join(dirpath, rule_filename)\n+ rule_file_path = os.path.abspath(rule_file_path)\n+ logging.info('[sigma] Reading rules from {0!s}'.format(\n+ rule_file_path))\n+ with open(rule_file_path, 'r') as rule_file:\n+ try:\n+ rule_file_content = rule_file.read()\n+ parser = sigma_collection.SigmaCollectionParser(\n+ rule_file_content, sigma_config, None)\n+ parsed_sigma_rules = parser.generate(sigma_backend)\n+ except (NotImplementedError) as exception:\n+ logging.error(\n+ '{0:s} Error NotImplementedError generating rule in file {1:s}: {1!s}'\n+ .format(rule_filename,rule_file_path, exception))\n+ sigma_rules_with_problems.append(rule_file_path)\n+ continue\n+ except (sigma.parser.exceptions.SigmaParseError) as exception:\n+ logging.error(\n+ '{0:s} Error generating rule in file {1:s} '\n+ 'you should not use this rule in Timesketch: {2!s}'\n+ .format(rule_filename,rule_file_path, exception))\n+ sigma_rules_with_problems.append(rule_file_path)\n+ continue\n+ sigma_verified_rules.append(rule_file_path)\n+ return sigma_verified_rules,sigma_rules_with_problems\n+\n+\n+if __name__ == '__main__':\n+ code_path = get_codepath()\n+ # We want to ensure our mocked libraries get loaded first.\n+ sys.path.insert(0, code_path)\n+\n+ description = (\n+ 'Mock an sigma analyzer run. This tool is intended for developers '\n+ 'of sigma rules as well as Timesketch server admins. '\n+ 'The tool can also be used for automatic testing to make sure the '\n+ 'rules are still working as intended.')\n+ epilog = (\n+ 'Remember to feed the tool with proper rule data.'\n+ )\n+\n+ arguments = argparse.ArgumentParser(\n+ description=description, allow_abbrev=True)\n+ arguments.add_argument(\n+ '--config_file', '--file', dest='config_file_path', action='store',\n+ default='', type=str, metavar='PATH_TO_TEST_FILE', help=(\n+ 'Path to the file containing the config data to feed sigma '\n+ ))\n+ arguments.add_argument(\n+ 'rules_path', action='store', default='', type=str,\n+ metavar='PATH_TO_RULES', help='Path to the rules to test.')\n+\n+ try:\n+ options = arguments.parse_args()\n+ except UnicodeEncodeError:\n+ print(arguments.format_help())\n+ sys.exit(1)\n+\n+ if not os.path.isfile(options.config_file_path):\n+ print('Config file not found.')\n+ sys.exit(1)\n+\n+ if not os.path.isdir(options.rules_path):\n+ print('The path to the analyzer file does not exist ({0:s})'.format(\n+ options.rules_path))\n+ sys.exit(1)\n+\n+ sigma_verified_rules, sigma_rules_with_problems = run_verifier(\n+ rules_path=options.rules_path,\n+ config_file_path=options.config_file_path)\n+\n+ print('You should NOT import the following rules')\n+ for badrule in sigma_rules_with_problems:\n+ print(badrule)\n" } ]
Python
Apache License 2.0
google/timesketch
Verify Sigma Rules test tool
263,095
15.07.2020 14:30:28
0
a060564d9f7050339b23479b5a04b8fbe9820df0
Fix an issue with unicode chars in sigma rules
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/sigma_tagger.py", "new_path": "timesketch/lib/analyzers/sigma_tagger.py", "diff": "@@ -5,6 +5,7 @@ import logging\nimport os\nimport time\nimport elasticsearch\n+import codecs\nfrom sigma.backends import elasticsearch as sigma_elasticsearch\n@@ -100,7 +101,8 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nrule_file_path = os.path.abspath(rule_file_path)\nlogging.info('[sigma] Reading rules from {0!s}'.format(\nrule_file_path))\n- with open(rule_file_path, 'r') as rule_file:\n+ with codecs.open(rule_file_path, 'r', encoding='utf-8',\n+ errors='replace') as rule_file:\ntry:\nrule_file_content = rule_file.read()\nparser = sigma_collection.SigmaCollectionParser(\n" } ]
Python
Apache License 2.0
google/timesketch
Fix an issue with unicode chars in sigma rules
263,095
15.07.2020 16:35:43
-7,200
7cd05d741a0f74f203819c729d635286466b06fc
fix and print good rules
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -98,7 +98,8 @@ def run_verifier(rules_path, config_file_path):\nrule_file_path = os.path.abspath(rule_file_path)\nlogging.info('[sigma] Reading rules from {0!s}'.format(\nrule_file_path))\n- with open(rule_file_path, 'r') as rule_file:\n+ with codecs.open(rule_file_path, 'r',\n+ encoding=\"utf-8\") as rule_file:\ntry:\nrule_file_content = rule_file.read()\nparser = sigma_collection.SigmaCollectionParser(\n@@ -108,9 +109,10 @@ def run_verifier(rules_path, config_file_path):\nlogging.error(\n'{0:s} Error NotImplementedError generating rule in file {1:s}: {1!s}'\n.format(rule_filename,rule_file_path, exception))\n+\nsigma_rules_with_problems.append(rule_file_path)\ncontinue\n- except (sigma.parser.exceptions.SigmaParseError) as exception:\n+ except (sigma.parser.exceptions.SigmaParseError, TypeError) as exception:\nlogging.error(\n'{0:s} Error generating rule in file {1:s} '\n'you should not use this rule in Timesketch: {2!s}'\n@@ -165,6 +167,11 @@ if __name__ == '__main__':\nrules_path=options.rules_path,\nconfig_file_path=options.config_file_path)\n- print('You should NOT import the following rules')\n+ print('### You should NOT import the following rules ###')\nfor badrule in sigma_rules_with_problems:\nprint(badrule)\n+\n+ print('### You can import the following rules ###')\n+ for goodrule in sigma_verified_rules:\n+ print(goodrule)\n+\n" } ]
Python
Apache License 2.0
google/timesketch
fix https://github.com/google/timesketch/pull/1308 and print good rules
263,095
15.07.2020 14:47:56
0
7c7e6de75bdf86060e77aa76aa731a4e1e06be51
timesketch/lib/analyzers/sigma_tagger.py:8:0: C0411: standard import "import codecs" should be placed before "import elasticsearch" (wrong-import-order)
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/sigma_tagger.py", "new_path": "timesketch/lib/analyzers/sigma_tagger.py", "diff": "@@ -4,8 +4,8 @@ from __future__ import unicode_literals\nimport logging\nimport os\nimport time\n-import elasticsearch\nimport codecs\n+import elasticsearch\nfrom sigma.backends import elasticsearch as sigma_elasticsearch\n" } ]
Python
Apache License 2.0
google/timesketch
timesketch/lib/analyzers/sigma_tagger.py:8:0: C0411: standard import "import codecs" should be placed before "import elasticsearch" (wrong-import-order)
263,095
15.07.2020 17:27:42
-7,200
25813295d8b08c559d60d671b6482c5eeb6a0b7b
fix a logic bug that caused a lot of errors not beeing appended to the actual array of problematic rules
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -25,13 +25,14 @@ import argparse\nimport sys\nimport codecs\n+import sigma.parser.exceptions\n+\nfrom sigma.backends import elasticsearch as sigma_elasticsearch\nimport sigma.configuration as sigma_configuration\nfrom sigma.parser import collection as sigma_collection\n-logging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"ERROR\"))\n-import sigma.parser.exceptions\n+logging.basicConfig(level=os.environ.get('LOGLEVEL', 'ERROR'))\ndef get_codepath():\n@@ -49,6 +50,7 @@ def get_codepath():\ndef run_verifier(rules_path, config_file_path):\n\"\"\"Run an sigma parsing test on a given dir and returns results from the run.\n+\nArgs:\nrules_path: the path to the rules.\nconfig_file_path: the path to a config file that contains mapping data.\n@@ -56,7 +58,7 @@ def run_verifier(rules_path, config_file_path):\nIOError: if the path to either test or analyzer file does not exist\nor if the analyzer module or class cannot be loaded.\nReturns:\n- two lists:\n+ a tuple of lists:\n- sigma_verified_rules with rules that can be added\n- sigma_rules_with_problems with rules that should not be added\n\"\"\"\n@@ -73,6 +75,8 @@ def run_verifier(rules_path, config_file_path):\nsigma_config_con = sigma_config_file.read()\nsigma_config = sigma_configuration.SigmaConfiguration(sigma_config_con)\nsigma_backend = sigma_elasticsearch.ElasticsearchQuerystringBackend(sigma_config, {})\n+ sigma_verified_rules = []\n+ sigma_rules_with_problems = []\nfor dirpath, dirnames, files in os.walk(rules_path):\n@@ -81,20 +85,17 @@ def run_verifier(rules_path, config_file_path):\nrule_extensions = (\"yml\",\"yaml\")\n- sigma_verified_rules = []\n- sigma_rules_with_problems = []\n-\nfor rule_filename in files:\nif rule_filename.lower().endswith(rule_extensions):\n# if a sub dir is found, append it to be scanned for rules\nif os.path.isdir(os.path.join(rules_path, rule_filename)):\n- logging.error(\n- 'this is a directory, skipping: {0:s}'.format(\n+ logging.debug(\n+ 'This is a directory, skipping: {0:s}'.format(\nrule_filename))\ncontinue\n- tag_name, _ = rule_filename.rsplit('.')\n+ tag_name, _, _ = rule_filename.rpartition('.')\nrule_file_path = os.path.join(dirpath, rule_filename)\nrule_file_path = os.path.abspath(rule_file_path)\nlogging.info('[sigma] Reading rules from {0!s}'.format(\n" } ]
Python
Apache License 2.0
google/timesketch
fix a logic bug that caused a lot of errors not beeing appended to the actual array of problematic rules
263,095
15.07.2020 17:36:00
-7,200
73577eff907f48a0a61b3c4a30375257e965cb38
fix some feedback from reviewer
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -98,7 +98,7 @@ def run_verifier(rules_path, config_file_path):\ntag_name, _, _ = rule_filename.rpartition('.')\nrule_file_path = os.path.join(dirpath, rule_filename)\nrule_file_path = os.path.abspath(rule_file_path)\n- logging.info('[sigma] Reading rules from {0!s}'.format(\n+ logging.debug('[sigma] Reading rules from {0:s}'.format(\nrule_file_path))\nwith codecs.open(rule_file_path, 'r',\nencoding=\"utf-8\") as rule_file:\n@@ -109,7 +109,7 @@ def run_verifier(rules_path, config_file_path):\nparsed_sigma_rules = parser.generate(sigma_backend)\nexcept (NotImplementedError) as exception:\nlogging.error(\n- '{0:s} Error NotImplementedError generating rule in file {1:s}: {1!s}'\n+ '{0:s} Error NotImplementedError generating rule in file {1:s}: {2!s}'\n.format(rule_filename,rule_file_path, exception))\nsigma_rules_with_problems.append(rule_file_path)\n" } ]
Python
Apache License 2.0
google/timesketch
fix some feedback from reviewer
263,095
03.08.2020 15:08:57
0
2f24ec878480b560f6eb8bd8d14ce820ddecaeb0
refactoring, introducing --info and --debug
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -45,23 +45,47 @@ def get_codepath():\nreturn sys_path\nreturn dirname\n-def verify_rules_file(rule_file_path):\n+def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\n\"\"\"Verifies a given file path contains a valid sigma rule.\nArgs:\nrule_file_path: the path to the rules.\n+ sigma_config: config to use\n+ sigma_backend: A sigma.backends instance\nRaises:\n- IOError: if the path to either test or analyzer file does not exist\n- or if the analyzer module or class cannot be loaded.\n+ None\nReturns:\ntrue: rule_file_path contains a valid sigma rule\nfalse: rule_file_path does not contain a valid sigma rule\n\"\"\"\n+ logging.debug('[sigma] Reading rules from {0:s}'.format(\n+ rule_file_path))\n- return true\n+ path, rule_filename = os.path.split(rule_file_path)\n+\n+ with codecs.open(rule_file_path, 'r', encoding=\"utf-8\") as rule_file:\n+ try:\n+ rule_file_content = rule_file.read()\n+ parser = sigma_collection.SigmaCollectionParser(\n+ rule_file_content, sigma_config, None)\n+ parsed_sigma_rules = parser.generate(sigma_backend)\n+ except (NotImplementedError) as exception:\n+ logging.error(\n+ '{0:s} Error with file {1:s}: {2!s}'.format\n+ (rule_filename, rule_file_path, exception))\n+ return False\n+ except (\n+ sigma.parser.exceptions.SigmaParseError, TypeError) as exception:\n+ logging.error(\n+ '{0:s} Error with file {1:s} '\n+ 'you should not use this rule in Timesketch: {2!s}'\n+ .format(rule_filename, rule_file_path, exception))\n+ return False\n+\n+ return True\ndef run_verifier(rules_path, config_file_path):\n@@ -94,8 +118,8 @@ def run_verifier(rules_path, config_file_path):\nsigma_config = sigma_configuration.SigmaConfiguration(sigma_config_con)\nsigma_backend = sigma_elasticsearch.\\\nElasticsearchQuerystringBackend(sigma_config, {})\n- sigma_verified_rules = []\n- sigma_rules_with_problems = []\n+ return_verified_rules = []\n+ return_rules_with_problems = []\nfor dirpath, dirnames, files in os.walk(rules_path):\n@@ -116,31 +140,14 @@ def run_verifier(rules_path, config_file_path):\nrule_file_path = os.path.join(dirpath, rule_filename)\nrule_file_path = os.path.abspath(rule_file_path)\n- logging.debug('[sigma] Reading rules from {0:s}'.format(\n- rule_file_path))\n- with codecs.open(rule_file_path, 'r',\n- encoding=\"utf-8\") as rule_file:\n- try:\n- rule_file_content = rule_file.read()\n- parser = sigma_collection.SigmaCollectionParser(\n- rule_file_content, sigma_config, None)\n- parsed_sigma_rules = parser.generate(sigma_backend)\n- except (NotImplementedError) as exception:\n- logging.error(\n- '{0:s} Error NotImplementedError generating rule in file {1:s}: {2!s}'\n- .format(rule_filename,rule_file_path, exception))\n- sigma_rules_with_problems.append(rule_file_path)\n- continue\n- except (sigma.parser.exceptions.SigmaParseError, TypeError) as exception:\n- logging.error(\n- '{0:s} Error generating rule in file {1:s} '\n- 'you should not use this rule in Timesketch: {2!s}'\n- .format(rule_filename,rule_file_path, exception))\n- sigma_rules_with_problems.append(rule_file_path)\n- continue\n- sigma_verified_rules.append(rule_file_path)\n- return sigma_verified_rules,sigma_rules_with_problems\n+ if verify_rules_file(rule_file_path, sigma_config, sigma_backend):\n+ return_verified_rules.append(rule_file_path)\n+ else:\n+ logging.info('File did not work{0:s}'.format(rule_file_path))\n+ return_rules_with_problems.append(rule_file_path)\n+\n+ return return_verified_rules, return_rules_with_problems\nif __name__ == '__main__':\n@@ -167,13 +174,22 @@ if __name__ == '__main__':\narguments.add_argument(\n'rules_path', action='store', default='', type=str,\nmetavar='PATH_TO_RULES', help='Path to the rules to test.')\n-\n+ arguments.add_argument(\n+ '--debug', action='store_true', help='print debug messages ')\n+ arguments.add_argument(\n+ '--info', action='store_true', help='print info messages ')\ntry:\noptions = arguments.parse_args()\nexcept UnicodeEncodeError:\nprint(arguments.format_help())\nsys.exit(1)\n+ if options.debug:\n+ logging.getLogger().setLevel(logging.DEBUG)\n+\n+ if options.info:\n+ logging.getLogger().setLevel(logging.INFO)\n+\nif not os.path.isfile(options.config_file_path):\nprint('Config file not found.')\nsys.exit(1)\n@@ -194,4 +210,3 @@ if __name__ == '__main__':\nprint('### You can import the following rules ###')\nfor goodrule in sigma_verified_rules:\nprint(goodrule)\n-\n" } ]
Python
Apache License 2.0
google/timesketch
refactoring, introducing --info and --debug
263,095
03.08.2020 15:14:56
0
c08310e85aa2b33e8d0a8b66b35260647381a60a
pylint fixes[3~
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -72,17 +72,16 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\nparser = sigma_collection.SigmaCollectionParser(\nrule_file_content, sigma_config, None)\nparsed_sigma_rules = parser.generate(sigma_backend)\n- except (NotImplementedError) as exception:\n+ except (NotImplementedError) as e:\nlogging.error(\n'{0:s} Error with file {1:s}: {2!s}'.format\n- (rule_filename, rule_file_path, exception))\n+ (rule_filename, rule_file_path, e))\nreturn False\n- except (\n- sigma.parser.exceptions.SigmaParseError, TypeError) as exception:\n+ except (sigma.parser.exceptions.SigmaParseError, TypeError) as e:\nlogging.error(\n'{0:s} Error with file {1:s} '\n'you should not use this rule in Timesketch: {2!s}'\n- .format(rule_filename, rule_file_path, exception))\n+ .format(rule_filename, rule_file_path, e))\nreturn False\nreturn True\n" } ]
Python
Apache License 2.0
google/timesketch
pylint fixes[3~
263,095
04.08.2020 12:46:13
0
361b34b909c0958a9d7d2610f25ba1e42765313e
introduce rule_id and clear up debug / info output
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "\"\"\"A tool to test sigma rules.\nThis tool can be used to verify your rules before running an analyzer.\nIt also does not require you to have a full blown Timesketch instance.\n+Default this tool will show only the rules that cause problems.\nExample way of running the tool:\n$ sigma_verify_rules.py --config_file ../data/sigma_config.yaml ../data/linux/\n\"\"\"\n@@ -71,14 +72,27 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\nrule_file_content = rule_file.read()\nparser = sigma_collection.SigmaCollectionParser(\nrule_file_content, sigma_config, None)\n+\n+ # trying to get the sigma rule id\n+ for element in parser.parsers:\n+ logging.info('Rule Id: {0:s}'.format(element.parsedyaml['id']))\nparsed_sigma_rules = parser.generate(sigma_backend)\n+ for sigma_rule in parsed_sigma_rules:\n+ # TODO Investigate how to handle .keyword\n+ # fields in Sigma.\n+ # https://github.com/google/timesketch/issues/1199#issuecomment-639475885\n+ sigma_rule = sigma_rule \\\n+ .replace(\".keyword:\", \":\")\n+ logging.info(\n+ '{0:s} Generated query {1:s}'\n+ .format(rule_file_path, sigma_rule))\nexcept (NotImplementedError) as e:\n- logging.error(\n+ logging.info(\n'{0:s} Error with file {1:s}: {2!s}'.format\n(rule_filename, rule_file_path, e))\nreturn False\nexcept (sigma.parser.exceptions.SigmaParseError, TypeError) as e:\n- logging.error(\n+ logging.info(\n'{0:s} Error with file {1:s} '\n'you should not use this rule in Timesketch: {2!s}'\n.format(rule_filename, rule_file_path, e))\n@@ -202,10 +216,13 @@ if __name__ == '__main__':\nrules_path=options.rules_path,\nconfig_file_path=options.config_file_path)\n+ if len(sigma_rules_with_problems) > 0:\nprint('### You should NOT import the following rules ###')\n+ print('### To get the reason per rule, re-run with --info###')\nfor badrule in sigma_rules_with_problems:\nprint(badrule)\n- print('### You can import the following rules ###')\n+ if len(sigma_verified_rules) > 0:\n+ logging.info('### You can import the following rules ###')\nfor goodrule in sigma_verified_rules:\n- print(goodrule)\n+ logging.info(goodrule)\n" } ]
Python
Apache License 2.0
google/timesketch
introduce rule_id and clear up debug / info output
263,133
04.08.2020 16:32:28
0
0fa1ce36514caf49136a422b5711621637ee4027
Adding scrolling support into exports.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -1217,19 +1217,19 @@ class Sketch(resource.BaseResource):\n'Unable to search for labels in an archived sketch.')\nquery = {\n- \"nested\": {\n- \"path\": \"timesketch_label\",\n- \"query\": {\n- \"bool\": {\n- \"must\": [\n+ 'nested': {\n+ 'path': 'timesketch_label',\n+ 'query': {\n+ 'bool': {\n+ 'must': [\n{\n- \"term\": {\n- \"timesketch_label.name\": label_name\n+ 'term': {\n+ 'timesketch_label.name': label_name\n}\n},\n{\n- \"term\": {\n- \"timesketch_label.sketch_id\": self.id\n+ 'term': {\n+ 'timesketch_label.sketch_id': self.id\n}\n}\n]\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/archive.py", "new_path": "timesketch/api/v1/resources/archive.py", "diff": "@@ -470,21 +470,48 @@ class SketchArchiveResource(resources.ResourceMixin, Resource):\nif not indices or '_all' in indices:\nindices = self.sketch_indices\n+ # Ignoring the size limits in views to reduce the amount of queries\n+ # needed to get all the data.\n+ query_filter['terminate_after'] = 10000\n+ query_filter['size'] = 10000\n+\nquery_dsl = view.query_dsl\nif query_dsl:\nquery_dict = json.loads(query_dsl)\nif not query_dict:\nquery_dsl = None\n- # TODO (kiddi): Enable scrolling support.\nresult = self.datastore.search(\nsketch_id=sketch.id,\nquery_string=view.query_string,\nquery_filter=query_filter,\nquery_dsl=query_dsl,\n+ enable_scroll=True,\nindices=indices)\n+ scroll_id = result.get('_scroll_id', '')\n+ if scroll_id:\n+ data_frame = _query_results_to_dataframe(result, sketch)\n+\n+ total_count = result.get(\n+ 'hits', {}).get('total', {}).get('value', '')\n+ event_count = len(result['hits']['hits'])\n+\n+ while event_count < total_count:\n+ # pylint: disable=unexpected-keyword-arg\n+ result = self.datastore.client.scroll(\n+ scroll_id=scroll_id, scroll='1m')\n+ event_count += len(result['hits']['hits'])\n+ add_frame = _query_results_to_dataframe(result, sketch)\n+ if add_frame.shape[0]:\n+ data_frame = pd.concat([data_frame, add_frame], sort=False)\n+\n+ fh = io.StringIO()\n+ data_frame.to_csv(fh, index=False)\n+ fh.seek(0)\n+ else:\nfh = _query_results_to_filehandle(result, sketch)\n+\nzip_file.writestr(\n'views/{0:s}.csv'.format(name), data=fh.read())\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/datastores/elastic.py", "new_path": "timesketch/lib/datastores/elastic.py", "diff": "@@ -95,7 +95,7 @@ class ElasticsearchDataStore(object):\nlabel_query = {\n'bool': {\n'should': [],\n- \"minimum_should_match\": 1\n+ 'minimum_should_match': 1\n}\n}\n@@ -205,7 +205,7 @@ class ElasticsearchDataStore(object):\ndatetime_ranges = {\n'bool': {\n'should': [],\n- \"minimum_should_match\": 1\n+ 'minimum_should_match': 1\n}\n}\n" } ]
Python
Apache License 2.0
google/timesketch
Adding scrolling support into exports.
263,133
05.08.2020 14:20:14
0
ffe48bd91bbbea2a56cfb5f993225ccb49d04779
Create APIClient.md
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/APIClient.md", "diff": "+# API Client\n+\n+The API client is a set of Python libraries that can be used to interact with the REST API of Timesketch from notebooks or scripts. It takes\n+care of setting up authentication, sending the API calls to the server, error handling, and presentation.\n+\n+This is not meant to be a full fledged documentation of the API client, but rather a starting point for people on how to use the API client in\n+a script. The same methods can be used for interactions in a notebook, however those instructions are best left in a notebook (TODO: Create a\n+notebook and link to it here).\n+\n+## Basic Connections\n+\n+The API client defines a config library specifically intended to help with setting up all configuration for connecting to Timesketch, including\n+authentication and server information. The config client will read stored connection information from `~/.timesketchrc`, asking the user questions\n+if information is missing (and subsequently storing the results of those questions in the RC file for future lookups).\n+\n+An example use of the config client:\n+\n+```\n+from timesketch_api_client import config\n+\n+ts_client = config.get_client()\n+```\n+\n+To be able to take advantage of the config client, the user needs to be running this from the command line or in a way where questions can be asked\n+and answered (or the config file to be fully populated). This works both in CLI scripts as well as in a notebook.\n+\n+By default the client credentials will be stored on disk in a Token file, in an encrypted format, protected by a randomly generated\n+password that is stored in the RC file. It is highly recommended to protect your credential file using a strong password. The password\n+for the file can be passed on to the config class using:\n+\n+```\n+ts_client = config.get_client(token_password='MY_SUPER_L337_PWD')\n+```\n+\n+If the token file does not exist, it will be generated and encrypted using the supplied password.\n+\n+### Using the Timesketch Client\n+\n+The TS client only has limited functionality, such as to list open indices, what sketches the user has access to as well as to fetch sketches, indices, etc.\n+The client object also contains functions to check for OAUTH token status and refresh it, if needed.\n+\n+Most of the functionality of the API client lies in sketch operations. To list all available sketches the function `list_sketches` can be used:\n+\n+```\n+for sketch in ts_client.list_sketches():\n+ # Do something with the sketches...\n+```\n+\n+To print the name and description of all available sketches, something like:\n+\n+```\n+for sketch in ts_client.list_sketches():\n+ print('[{0:d}] {1:s} <{2:s}>'.format(sketch.id, sketch.name, sketch.description))\n+```\n+\n+## Connecting to a Sketch\n+\n+There are two ways of getting a sketch object, either by listing all available sketches or by fetching a specific one.\n+To fetch a specific one use the `get_sketch` function:\n+\n+```\n+sketch = ts_client.get_sketch(SKETCH_ID)\n+```\n+\n+All you need is the sketch ID, eg:\n+\n+```\n+sketch = ts_client.get_sketch(25)\n+```\n+\n+## Overview of a Sketch\n+\n+A sketch object has few properties that can be used to get a better overview of what it contains:\n+\n++ **acl**: A python dict with the current sketch ACL.\n++ **labels**: A list of strings, with all the labels that are attached to the sketch.\n++ **name**: The name of the sketch.\n++ **description**: The description of the sketch.\n++ **status**: The status of the sketch.\n+\n+Each of these properties can be accessed using `sketch.<PROPERTY>`, eg. `sketch.name`, or `sketch.labels`\n+\n+## Explore Data\n+\n+The sketch object has several ways to explore data, via aggregations or searches.\n+\n+### Views\n+\n+The first is simply to list up all views... the function `list_views` returns back View object for all views. An example overview would be:\n+\n+```\n+for view in sketch.list_views():\n+ print('{0:03d} - {1:s} [{2:s}]'.format(view.id, view.name, view.user))\n+```\n+\n+It is also possible to create a new view:\n+\n+```\n+view = sketch.create_view(name, query_string='', query_dsl='', query_filter=None)\n+```\n+\n+Which can be as simple as:\n+\n+```\n+view = sketch.create_view('Google mentions', query_string='google.com')\n+```\n+\n+To get a view that has been saved:\n+\n+```\n+view = sketch.get_view(view_id=<VIEW_ID>)\n+```\n+\n+or\n+\n+```\n+view = sketch.get_view(view_name=<VIEW_NAME>)\n+```\n+\n+A view object can be used like this:\n+\n+```\n+data = sketch.explore(view=view, as_pandas=True)\n+```\n+\n+The results will be a pandas DataFrame that contains all the records from a view.\n+\n+### Search Query\n+\n+To search in the API client the function `sketch.explore` is used. It will accept several parameters, such as a view object if that is available\n+or a free flowing query string (same as in the UI) or a raw Elastic query DSL.\n+\n+The output can be:\n++ A pandas DataFrame if the `as_pandas=True` is set\n++ A python dict (default behavior)\n++ All output stored to a file if the parameter `file_name='FILEPATH.zip'` is supplied.\n+\n+There are also other parameters to the explore function that are worth a mention:\n++ **query_filter**: possible to customize the query filter, to limit search results, include extra fields in the results, etc\n++ **return_fields**: A comma separated string that contains a list of the fields/columns you want returned. By default only\n+a limited set of columns are returned. To expand on that use this variable to list up the columns you need.\n++ **max_entries**: an integer that determines the maximum amount of entries you want returned back. The default value here is 10k\n+events. There may be a bit more events returned than this number determines, it is a best effort but should be used if you don't want\n+all the events returned back, only a fraction of them.\n+\n+An example of a search query:\n+\n+```\n+data = sketch.explore('google.com', as_pandas=True)\n+```\n+\n+This will return back a pandas DataFrame with the search results.\n+\n+### Aggregations\n+\n+Another option to explore the data is via aggregations. To get a list of available aggregators use:\n+\n+```\n+sketch.list_available_aggregators()\n+```\n+\n+What gets returned back is a pandas DataFrame with all the aggregators and what parameters they need in order to work.\n+\n+An example aggregation is:\n+\n+```\n+params = {\n+ 'field': 'domain',\n+ 'limit': 10,\n+ 'supported_charts': 'hbarchart',\n+}\n+\n+aggregation = sketch.run_aggregator(aggregator_name='field_bucket', aggregator_parameters=params)\n+```\n+\n+This will return back an aggregation object that can be used to display the data, eg in a pandas DataFrame\n+\n+```\n+df = aggregation.table\n+```\n+\n+Or as a chart\n+\n+```\n+aggregation.chart\n+```\n+\n+\n+\n+### Other Options\n+\n+The sketch object can be used to do several other actions that are not documented in this first document, such as:\n++ Create/list/retrieve stories\n++ Manually add events to the sketch\n++ Add timelines to the sketch\n++ Modify the ACL of the sketch\n++ Archive the sketch (via the `sketch.archive` function)\n++ Comment on an event\n++ Delete a sketch\n++ Export the sketch data\n++ Run analyzers on the sketch.\n" } ]
Python
Apache License 2.0
google/timesketch
Create APIClient.md
263,096
10.08.2020 13:50:13
-7,200
a6b23e083645555ed5596dc89a0efff8bf7a3799
Mention the minimal RAM needed
[ { "change_type": "MODIFY", "old_path": "docs/Installation.md", "new_path": "docs/Installation.md", "diff": "# Install Timesketch from scratch\n+NOTE: It is not recommended to try to run on a system with less than 8 GB of RAM.\n+\n#### Install Ubuntu\nThis installation guide is based on Ubuntu 18.04LTS Server edition. Follow the installation guide for Ubuntu and install the base system.\n" } ]
Python
Apache License 2.0
google/timesketch
Mention the minimal RAM needed https://github.com/google/timesketch/issues/924
263,095
10.08.2020 14:41:59
-7,200
bd96fd625f466e4e07cd9cec62bccc3cd65bd64e
introduce unit tests
[ { "change_type": "ADD", "old_path": null, "new_path": "test_tools/sigma_verify_rules_test.py", "diff": "+\"\"\"Tests for Sigma Verify tool.\"\"\"\n+from __future__ import unicode_literals\n+\n+import unittest\n+\n+from sigma_verify_rules import *\n+\n+class TestSigmaVerifyRules(unittest.TestCase):\n+ def test_get_code_path(self):\n+ \"\"\"Test the get code path function.\"\"\"\n+ code_path_output = get_codepath\n+ logging.info(\"asd\")\n+ self.assertIsNotNone(code_path_output)\n+\n+ def test_verify_rules_file(self):\n+ \"\"\"Test some of the verify rules code.\"\"\"\n+\n+ self.assertFalse(verify_rules_file(\"foo\", \"bar\", None))\n+ self.assertFalse(verify_rules_file(\"../data/sigma/rules/\", \"../data/sigma_config.yaml\", None))\n+\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n+\n" } ]
Python
Apache License 2.0
google/timesketch
introduce unit tests
263,095
12.08.2020 14:45:06
-7,200
b73af73518e2f58948e286efd6693ab53fae0ce5
remove heatmap and manual events from userdoc
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "## Table of Contents\n-1. [Demo](#demo)\n-2. [tsctl](#tsctl)\n+- [Table of Contents](#table-of-contents)\n+- [Demo](#demo)\n+- [tsctl](#tsctl)\n- [Start timesketch](#start-timesketch)\n- [User management](#user-management)\n- [Adding users](#adding-users)\n- [Change user password](#change-user-password)\n- [Removing users](#removing-users)\n- - [Group Management](#group-management)\n+ - [Group management](#group-management)\n- [Adding groups](#adding-groups)\n- [Removing groups](#removing-groups)\n- [Managing group membership](#managing-group-membership)\n- - [Add index](#add_index)\n- - [Migrate database](#migrate-db)\n+ - [add_index](#add_index)\n+ - [Migrate db](#migrate-db)\n- [Drop database](#drop-database)\n- - [Import JSON to timesketch](#import-json-to-timesketch)\n+ - [Import json to Timesketch](#import-json-to-timesketch)\n- [Purge](#purge)\n- - [Search template](#search_template)\n- - [Import](#import)\n+ - [search_template](#search_template)\n+ - [import](#import)\n- [similarity_score](#similarity_score)\n-3. [Concepts](#concepts)\n+- [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)\n-4. [Searching](#searching)\n+- [Searching](#searching)\n## Demo\n@@ -260,10 +260,10 @@ There is a dedicated document to walk you through [Sketches](/docs/SketchOvervie\n### Adding event\n-To manually adding an event, visit the sketch view. Within that screen, there is the possibility to star an event, hide an event as well as add a manual event (marked with a little +).\n-This event will have the previously selected time pre-filled but can be changed.\n+*This feature is currently not implemented in the Web UI*\n-![Add event screenshot](/docs/add_event.png)\n+~~To manually adding an event, visit the sketch view. Within that screen, there is the possibility to star an event, hide an event as well as add a manual event (marked with a little +).\n+This event will have the previously selected time pre-filled but can be changed.~~\n### Views\n@@ -277,7 +277,9 @@ Hit the big red button to show/hide the events.\n### Heatmap\n-The heatmap aggregation calculates on which day of the week and at which hour events happened. This can be very useful e.g. when analyzing lateral movement or login events.\n+*This feature is currently not implemented in the Web UI*\n+\n+~~The heatmap aggregation calculates on which day of the week and at which hour events happened. This can be very useful e.g. when analyzing lateral movement or login events.~~\n### Stories\n" } ]
Python
Apache License 2.0
google/timesketch
remove heatmap and manual events from userdoc
263,095
14.08.2020 14:39:31
-7,200
ac01520faca6be759df2209b7d7d2a8dad36fc99
mention Analyzers
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Heatmap](#heatmap)\n- [Stories](#stories)\n- [Searching](#searching)\n+- [Analyzers](#analyzers)\n+\n## Demo\n@@ -316,3 +318,23 @@ Using the advances search, a JSON can be passed to Timesketch\n}\n}\n```\n+\n+## Analyzers\n+\n+With Analyzers you can enrich your data in timelines. The analysers are written in Python.\n+\n+The systems consist of a set of background workers that can execute Python code on a stream of events. It provides an easy to use API to programmatically do all the actions available in the UI, e.g. tagging events, star and create saved views etc. The idea is to automatically enrich data with encoded analysis knowledge.\n+\n+### Activate Analyzers\n+\n+To use Analyzers, celery workers need to run.\n+\n+To run a Celery worker process:\n+\n+```\n+$ celery -A timesketch.lib.tasks worker --loglevel=info\n+```\n+\n+Read on how to run the Celery worker in the background over at the official [Celery documentation](http://docs.celeryproject.org/en/latest/userguide/daemonizing.html#daemonizing).\n+\n+To start the worker in Docker, please see [Docker readme](docker/dev/README.md#start-a-celery-container-shell)\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
mention Analyzers
263,095
14.08.2020 14:51:50
-7,200
e810c09b27d174d28fe178484ca03caddd76eb8d
cover the first few analyzers
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Searching](#searching)\n- [Analyzers](#analyzers)\n-\n-\n## Demo\nTo play with timesketch without any installation visit [demo.timesketch.org](https://demo.timesketch.org)\n@@ -338,3 +336,34 @@ $ celery -A timesketch.lib.tasks worker --loglevel=info\nRead on how to run the Celery worker in the background over at the official [Celery documentation](http://docs.celeryproject.org/en/latest/userguide/daemonizing.html#daemonizing).\nTo start the worker in Docker, please see [Docker readme](docker/dev/README.md#start-a-celery-container-shell)\n+\n+### Develop Analyzers\n+\n+There is a dedicated document to walk you through the process of developing [Analyzers](/docs/WriteAnalyzers.md)\n+\n+### Analyzer description\n+\n+#### Browser Search Analyzer\n+\n+The browser search analyzer takes URLs usually resevered for browser search queries and extracts the search string.\n+\n+It will also tell in a story:\n+\n+- The top 20 most commonly discovered searches\n+- The domains used to search\n+- The most common days of search\n+- And an overview of all the discovered search terms\n+\n+#### Browser Timeframe Analyzer\n+\n+The browser timeframe analyzer discovers browser events that ocurred outside of the typical browsing window of this browser history.\n+\n+The analyzer determines the activity hours by finding the frequency of browsing events per hour, and then discovering the longest block of most active hours before proceeding with flagging all events outside of that time period. This information can be used by other analyzers or by manually looking for other activity within the inactive time period to find unusual actions.\n+\n+#### Sigma Analyzer\n+\n+The Sigma Analyzer translates Sigma rules in Elastic Search Queries and adds a tag to every matching event.\n+\n+It will also create a story with the Top 10 matched Sigma rules.\n+\n+There is a dedicated document to walk you through the process of using the [Sigma Analyzer](/docs/UseSigmaAnalyzer.md).\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
cover the first few analyzers
263,133
14.08.2020 13:43:58
0
748153e98ca5697f7b0896baa98b64cc88898578
Removing timestamp from the EVTX chart
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/win_evtxgap.py", "new_path": "timesketch/lib/analyzers/win_evtxgap.py", "diff": "@@ -244,6 +244,8 @@ class EvtxGapPlugin(interface.BaseSketchAnalyzer):\ndf_append = pd.DataFrame(rows_to_append)\nevent_count = event_count.append(df_append, sort=False)\nevent_count.sort_values(by='day', inplace=True)\n+ if 'timestamp' in event_count:\n+ del event_count['timestamp']\nif event_count.shape[0]:\nparams = {\n" } ]
Python
Apache License 2.0
google/timesketch
Removing timestamp from the EVTX chart (#1337)
263,095
14.08.2020 16:42:15
-7,200
1856933850a645a198beaae725f8528ce78c7303
more analyzers, linters and some re-ordering in the userdoc
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "## Table of Contents\n+\n- [Table of Contents](#table-of-contents)\n+- [Concepts](#concepts)\n+ - [Sketches](#sketches)\n+ - [Adding Timelines](#adding-timelines)\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)\n- [Demo](#demo)\n- [tsctl](#tsctl)\n- [Start timesketch](#start-timesketch)\n- [search_template](#search_template)\n- [import](#import)\n- [similarity_score](#similarity_score)\n-- [Concepts](#concepts)\n- - [Sketches](#sketches)\n- - [Adding Timelines](#adding-timelines)\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)\n- [Searching](#searching)\n- [Analyzers](#analyzers)\n+ - [Develop Analyzers](#develop-analyzers)\n+ - [Analyzer description](#analyzer-description)\n+ - [Browser Search Analyzer](#browser-search-analyzer)\n+ - [Browser Timeframe Analyzer](#browser-timeframe-analyzer)\n+ - [Chain alanyzer](#chain-alanyzer)\n+ - [Domain Analyzer](#domain-analyzer)\n+ - [Windows EVTX Sessionizer](#windows-evtx-sessionizer)\n+ - [Windows EVTX Gap analyzer](#windows-evtx-gap-analyzer)\n+ - [Safebrowsing Analyzer](#safebrowsing-analyzer)\n+ - [Sigma Analyzer](#sigma-analyzer)\n+ - [YetiIndicators Analyzer](#yetiindicators-analyzer)\n+\n+## Concepts\n+\n+Timesketch is built on multiple sketches, where one sketch is usually one case.\n+Every sketch can consist of multiple timelines with multiple views.\n+\n+### Sketches\n+\n+There is a dedicated document to walk you through [Sketches](/docs/SketchOverview.md)\n+\n+### Adding Timelines\n+\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+\n+### Adding event\n+\n+*This feature is currently not implemented in the Web UI*\n+\n+~~To manually adding an event, visit the sketch view. Within that screen, there is the possibility to star an event, hide an event as well as add a manual event (marked with a little +).\n+This event will have the previously selected time pre-filled but can be changed.~~\n+\n+### Views\n+\n+#### Hiding events from a view\n+\n+All about reducing noise in the result views.\n+Hit the little eye to hide events from the list making it possible to\n+curate views to emphasize the important things.\n+The events are still there and can be easily shown for those who want to see them.\n+Hit the big red button to show/hide the events.\n+\n+### Heatmap\n+\n+*This feature is currently not implemented in the Web UI*\n+\n+~~The heatmap aggregation calculates on which day of the week and at which hour events happened. This can be very useful e.g. when analyzing lateral movement or login events.~~\n+\n+### Stories\n+\n+A story is a place where you can capture the narrative of your technical investigation and add detail to your story with raw timeline data.\n+The editor let you to write and capture the story behind your investigation and at the same time enable you to share detailed findings without spending hours writing reports.\n+\n+you can add events from previously saved searches.\n+Just hit enter to start a new paragraph and choose the saved search from the dropdown menu.\n+\n+See [Medium article](https://medium.com/timesketch/timesketch-2016-7-db3083e78156)\n+\n## Demo\n@@ -107,12 +168,14 @@ Not yet implemented.\n#### Adding groups\nCommand:\n-```\n+\n+```shell\ntsctl add_group\n```\nParameters:\n-```\n+\n+```shell\n--name / -n\n```\n@@ -126,19 +189,22 @@ Add or remove a user to a group. To add a user, specify the group and user. To\nremove a user, include the -r option.\nCommand:\n-```\n+\n+```shell\ntsctl manage_group\n```\nParameters:\n-```\n+\n+```shell\n--remove / -r (optional)\n--group / -g\n--user / -u\n```\nExample:\n-```\n+\n+```shell\ntsctl manage_group -u user_foo -g group_bar\n```\n@@ -147,26 +213,30 @@ tsctl manage_group -u user_foo -g group_bar\nCreate a new Timesketch searchindex.\nCommand:\n-```\n+\n+```shell\ntsctl add_index\n```\nParameters:\n-```\n+\n+```shell\n--name / -n\n--index / -i\n--user / -u\n```\nExample:\n-```\n+\n+```shell\ntsctl add_index -u user_foo -i test_index_name -n sample\n```\n### Migrate db\nCommand:\n-```\n+\n+```shell\ntsctl db\n```\n@@ -175,14 +245,16 @@ tsctl db\nWill drop all databases.\nComand:\n-```\n+\n+```shell\ntsctl drop_db\n```\n### Import json to Timesketch\nCommand:\n-```\n+\n+```shell\ntsctl json2ts\n```\n@@ -190,11 +262,14 @@ tsctl json2ts\nDelete 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+````\nArgs:\nindex_name: The name of the index in Elasticsearch\n+````\nComand:\n-```\n+\n+```shell\ntsctl purge\n```\n@@ -203,12 +278,14 @@ tsctl purge\nExport/Import search templates to/from file.\nCommand:\n-```\n+\n+```shell\ntsctl search_template\n```\nParameters:\n-```\n+\n+```shell\n--import / -i\n--export / -e\n```\n@@ -221,12 +298,14 @@ export_location: Path to the yaml file to export templates.\nCreates a new Timesketch timeline from a file. Supported file formats are: plaso, csv and jsonl.\nCommand:\n-```\n+\n+```shell\ntsctl import\n```\nParameters:\n-```\n+\n+```shell\n--file / -f\n--sketch_id / -s (optional)\n--username / -f (optional)\n@@ -235,62 +314,14 @@ Parameters:\nThe 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### similarity_score\nCommand:\n-```\n+\n+```shell\ntsctl similarity_score\n```\n-## Concepts\n-\n-Timesketch is built on multiple sketches, where one sketch is usually one case.\n-Every sketch can consist of multiple timelines with multiple views.\n-\n-### Sketches\n-\n-There is a dedicated document to walk you through [Sketches](/docs/SketchOverview.md)\n-\n-### Adding Timelines\n-\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-\n-### Adding event\n-\n-*This feature is currently not implemented in the Web UI*\n-\n-~~To manually adding an event, visit the sketch view. Within that screen, there is the possibility to star an event, hide an event as well as add a manual event (marked with a little +).\n-This event will have the previously selected time pre-filled but can be changed.~~\n-\n-### Views\n-\n-#### Hiding events from a view\n-\n-All about reducing noise in the result views.\n-Hit the little eye to hide events from the list making it possible to\n-curate views to emphasize the important things.\n-The events are still there and can be easily shown for those who want to see them.\n-Hit the big red button to show/hide the events.\n-\n-### Heatmap\n-\n-*This feature is currently not implemented in the Web UI*\n-\n-~~The heatmap aggregation calculates on which day of the week and at which hour events happened. This can be very useful e.g. when analyzing lateral movement or login events.~~\n-\n-### Stories\n-\n-A story is a place where you can capture the narrative of your technical investigation and add detail to your story with raw timeline data.\n-The editor let you to write and capture the story behind your investigation and at the same time enable you to share detailed findings without spending hours writing reports.\n-\n-you can add events from previously saved searches.\n-Just hit enter to start a new paragraph and choose the saved search from the dropdown menu.\n-\n-See [Medium article](https://medium.com/timesketch/timesketch-2016-7-db3083e78156)\n-\n## Searching\nThere is a dedicated document called [SearchQueryGuide](/docs/SearchQueryGuide.md) to help you create custom searches.\n@@ -298,6 +329,7 @@ There is a dedicated document called [SearchQueryGuide](/docs/SearchQueryGuide.m\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+\n```json\n{\n\"query\": {\n@@ -325,30 +357,18 @@ The systems consist of a set of background workers that can execute Python code\nThe code for Analyzers is located at\n-```\n+```shell\n/timesketch/lib/analyzers\n```\n-### Activate Analyzers\n-\n-To use Analyzers, celery workers need to run.\n-\n-To run a Celery worker process:\n-\n-```\n-$ celery -A timesketch.lib.tasks worker --loglevel=info\n-```\n-\n-Read on how to run the Celery worker in the background over at the official [Celery documentation](http://docs.celeryproject.org/en/latest/userguide/daemonizing.html#daemonizing).\n-\n-To start the worker in Docker, please see [Docker readme](docker/dev/README.md#start-a-celery-container-shell)\n-\n### Develop Analyzers\nThere is a dedicated document to walk you through the process of developing [Analyzers](/docs/WriteAnalyzers.md)\n### Analyzer description\n+*Note:* Not all analyzers are explained in this documentation. If you have questions to a particular analyzers, please have a look at the code or file an Issue on Github.\n+\n#### Browser Search Analyzer\nThe browser search analyzer takes URLs usually resevered for browser search queries and extracts the search string.\n@@ -382,10 +402,45 @@ It will also add information about:\n- Known CDN providers (based on timeskcteh config)\n-#### EVTX Sessionizer\n+#### Windows EVTX Sessionizer\nThis Analyzer will determine start end event for a user session based on EVTX events.\n+#### Windows EVTX Gap analyzer\n+\n+It attempts to detect gaps in EVTX files found in an index using two different methods.\n+\n+First of all it looks at missing entries in record numbers and secondly it attempts to look at gaps in days with no records.\n+\n+This may be an indication of someone clearing the logs, yet it may be an indication of something else. At least this should be interpreted as something that warrants a second look.\n+\n+This will obviously not catch every instance of someone clearing EVTX records, even if that's done in bulk. Therefore it should not be interpreted that if this analyzer does not discover something that the records have not been wiped. Please verify the results given by this analyzer.\n+\n+#### Safebrowsing Analyzer\n+\n+This Analyzer checks urls found in a sketch against the [Google Safebrowsing API](https://developers.google.com/safe-browsing/v4/reference/rest).\n+\n+To use this Analyzer, the following parameter must be set in the ````timesketch.conf````:\n+\n+````config\n+SAFEBROWSING_API_KEY = ''\n+````\n+\n+This analyzer can be customized by creating an optional file containing URL wildcards to be allow listed called\n+\n+````config\n+safebrowsing_allowlist.yaml\n+````\n+\n+There are also two additional config parameters, please refer to the [Safe Browsing API reference](https://developers.google.com/safe-browsing/v4/reference/rest).\n+\n+\n+Platforms to be looked at in Safe Browsing (PlatformType).\n+````SAFEBROWSING_PLATFORMS = ['ANY_PLATFORM']````\n+\n+Types to be looked at in Safe Browsing (ThreatType).\n+````SAFEBROWSING_THREATTYPES = ['MALWARE']````\n+\n#### Sigma Analyzer\nThe Sigma Analyzer translates Sigma rules in Elastic Search Queries and adds a tag to every matching event.\n@@ -393,3 +448,14 @@ The Sigma Analyzer translates Sigma rules in Elastic Search Queries and adds a t\nIt will also create a story with the Top 10 matched Sigma rules.\nThere is a dedicated document to walk you through the process of using the [Sigma Analyzer](/docs/UseSigmaAnalyzer.md).\n+\n+#### YetiIndicators Analyzer\n+\n+This is a Index analyzer for [Yeti](https://yeti-platform.github.io/) threat intel indicators.\n+\n+To use this Analyzer, the following parameter must be set with corresponding values in the ````timesketch.conf````:\n+\n+````config\n+YETI_API_ROOT = ''\n+YETI_API_KEY = ''\n+````\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
more analyzers, linters and some re-ordering in the userdoc
263,133
18.08.2020 10:36:19
0
cfe6072c20e2b3b7c23496611e00e78a6a3cbeb8
Changing exports to export all events and include all columns
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/export.py", "new_path": "timesketch/api/v1/export.py", "diff": "@@ -113,6 +113,78 @@ def export_story(story, sketch, story_exporter, zip_file):\ndata=exporter.export_story())\n+def query_to_filehandle(\n+ query_string='', query_dsl='', query_filter=None, sketch=None,\n+ datastore=None, indices=None):\n+ \"\"\"Query the datastore and return back a file object with the results.\n+\n+ This function takes a query string or DSL, queries the datastore\n+ and fetches all the events and stores them in a file-like object\n+ which gets returned back.\n+\n+ Args:\n+ query_string (str): Elasticsearch query string.\n+ query_dsl (str): Elasticsearch query DSL as JSON string.\n+ query_filter (dict): Filter for the query as a dict.\n+ sketch (timesketch.models.sketch.Sketch): a sketch object.\n+ datastore (elastic.ElasticsearchDataStore): the datastore object.\n+ indices (list): List of indices to query\n+\n+ Returns:\n+ file-like object in a CSV format with the results.\n+ \"\"\"\n+ # Ignoring the size limits to reduce the amount of queries\n+ # needed to get all the data.\n+ query_filter['terminate_after'] = 10000\n+ query_filter['size'] = 10000\n+\n+ result = datastore.search(\n+ sketch_id=sketch.id,\n+ query_string=query_string,\n+ query_filter=query_filter,\n+ query_dsl=query_dsl,\n+ enable_scroll=True,\n+ indices=indices)\n+\n+ scroll_id = result.get('_scroll_id', '')\n+ if not scroll_id:\n+ return query_results_to_filehandle(result, sketch)\n+\n+ data_frame = query_results_to_dataframe(result, sketch)\n+\n+ total_count = result.get(\n+ 'hits', {}).get('total', {}).get('value', 0)\n+\n+ if isinstance(total_count, str):\n+ try:\n+ total_count = int(total_count, 10)\n+ except ValueError:\n+ total_count = 0\n+\n+ event_count = len(result['hits']['hits'])\n+\n+ while event_count < total_count:\n+ # pylint: disable=unexpected-keyword-arg\n+ result = datastore.client.scroll(\n+ scroll_id=scroll_id, scroll='1m')\n+ event_count += len(result['hits']['hits'])\n+ add_frame = query_results_to_dataframe(result, sketch)\n+ if add_frame.shape[0]:\n+ data_frame = pd.concat([data_frame, add_frame], sort=False)\n+ else:\n+ logger.warning(\n+ 'Data Frame returned from a search operation was '\n+ 'empty, count {0:d} out of {1:d} total. Query is: '\n+ '\"{2:s}\"'.format(\n+ event_count, total_count,\n+ query_string or query_dsl))\n+\n+ fh = io.StringIO()\n+ data_frame.to_csv(fh, index=False)\n+ fh.seek(0)\n+ return fh\n+\n+\ndef query_results_to_dataframe(result, sketch):\n\"\"\"Returns a data frame from a Elastic query result dict.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/explore.py", "new_path": "timesketch/api/v1/resources/explore.py", "diff": "@@ -124,6 +124,34 @@ class ExploreResource(resources.ResourceMixin, Resource):\n}\n}\n+ if file_name:\n+ file_object = io.BytesIO()\n+\n+ form_data = {\n+ 'created_at': datetime.datetime.utcnow().isoformat(),\n+ 'created_by': current_user.username,\n+ 'sketch': sketch_id,\n+ 'query': form.query.data,\n+ 'query_dsl': query_dsl,\n+ 'query_filter': query_filter,\n+ 'return_fields': return_fields,\n+ }\n+ with zipfile.ZipFile(file_object, mode='w') as zip_file:\n+ zip_file.writestr('METADATA', data=json.dumps(form_data))\n+ fh = export.query_to_filehandle(\n+ query_string=form.query.data,\n+ query_dsl=query_dsl,\n+ query_filter=query_filter,\n+ indices=indices,\n+ sketch=sketch,\n+ datastore=self.datastore)\n+ fh.seek(0)\n+ zip_file.writestr('query_results.csv', fh.read())\n+ file_object.seek(0)\n+ return send_file(\n+ file_object, mimetype='zip',\n+ attachment_filename=file_name)\n+\nif scroll_id:\n# pylint: disable=unexpected-keyword-arg\nresult = self.datastore.client.scroll(\n@@ -196,28 +224,6 @@ class ExploreResource(resources.ResourceMixin, Resource):\nif isinstance(meta['es_total_count'], dict):\nmeta['es_total_count'] = meta['es_total_count'].get('value', 0)\n- if file_name:\n- file_object = io.BytesIO()\n- form_data = {\n- 'created_at': datetime.datetime.utcnow().isoformat(),\n- 'created_by': current_user.username,\n- 'sketch': sketch_id,\n- 'query': form.query.data,\n- 'query_dsl': query_dsl,\n- 'query_filter': query_filter,\n- 'return_fields': return_fields,\n- 'query_meta': meta,\n- }\n- with zipfile.ZipFile(file_object, mode='w') as zip_file:\n- zip_file.writestr('METADATA', data=json.dumps(form_data))\n- fh = export.query_results_to_filehandle(result, sketch)\n- fh.seek(0)\n- zip_file.writestr('query_results.csv', fh.read())\n- file_object.seek(0)\n- return send_file(\n- file_object, mimetype='zip',\n- attachment_filename=file_name)\n-\nschema = {'meta': meta, 'objects': result['hits']['hits']}\nreturn jsonify(schema)\n" } ]
Python
Apache License 2.0
google/timesketch
Changing exports to export all events and include all columns (#1342)
263,133
18.08.2020 12:58:15
0
c8ce85014bd5fffffd144d477c07e6884d61a03f
Removing 'from' keyword from query_filter
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/export.py", "new_path": "timesketch/api/v1/export.py", "diff": "@@ -138,6 +138,9 @@ def query_to_filehandle(\nquery_filter['terminate_after'] = 10000\nquery_filter['size'] = 10000\n+ if 'from' in query_filter:\n+ del query_filter['from']\n+\nresult = datastore.search(\nsketch_id=sketch.id,\nquery_string=query_string,\n" } ]
Python
Apache License 2.0
google/timesketch
Removing 'from' keyword from query_filter (#1344)
263,093
18.08.2020 15:00:35
-7,200
71bdf608eb0c42fd1fd41fb5e379fd4113c86d2f
no stats if new sketch
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/sketch.py", "new_path": "timesketch/api/v1/resources/sketch.py", "diff": "@@ -210,6 +210,7 @@ class SketchResource(resources.ResourceMixin, Resource):\n'data_types': []\n}\n+ if sketch_indices:\ntry:\nes_stats = self.datastore.client.indices.stats(\nindex=sketch_indices, metric='docs, store')\n@@ -243,7 +244,6 @@ class SketchResource(resources.ResourceMixin, Resource):\nindex=[index_name])\nstats_per_index[index_name]['data_types'] = result_obj.values\n-\nif not sketch_indices:\nmappings_settings = {}\nelse:\n" } ]
Python
Apache License 2.0
google/timesketch
no stats if new sketch (#1345)
263,095
20.08.2020 06:22:15
-7,200
87081e687c52b93e1c846de43106885e50f86aa4
Remove adding event ui stuff and adding mention of api client
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "@@ -58,10 +58,7 @@ There is a dedicated document to walk you through [Sketches](/docs/SketchOvervie\n### Adding event\n-*This feature is currently not implemented in the Web UI*\n-\n-~~To manually add an event, visit the sketch view. Within that screen, there is the possibility to star an event, hide an event as well as add a manual event (marked with a little +).\n-This event will have the previously selected time pre-filled but can be changed.~~\n+This feature is currently not implemented in the Web UI. But you can add events using the [API client](/docs/APIClient.md).\n### Views\n" } ]
Python
Apache License 2.0
google/timesketch
Remove adding event ui stuff and adding mention of api client https://github.com/google/timesketch/pull/1336#discussion_r473312362
263,095
20.08.2020 06:25:21
-7,200
26e88b74a05c409ed51b4999fb4ae7b28f1baf2e
mention how to export stories
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "@@ -90,6 +90,8 @@ You can add saved views, aggregations and text in markdown format to a story.\nSome analyzers automatically generate stories to either highlight possible events of interest or to document their runtime.\n+If you want to export a story, export the whole Sketch. The zip file will contain each story.\n+\n## Demo\nTo play with timesketch without any installation visit [demo.timesketch.org](https://demo.timesketch.org)\n" } ]
Python
Apache License 2.0
google/timesketch
mention how to export stories
263,095
20.08.2020 06:38:54
-7,200
3d3298094bcf6a572eb4614cab3da2d47e9a441d
explain what a view is
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Adding Timelines](#adding-timelines)\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)\n- [Demo](#demo)\n@@ -44,13 +43,9 @@ This feature is currently not implemented in the Web UI. But you can add events\n### Views\n-#### Hiding events from a view\n+Views are saved search queries. Those can either be created by the User, by API or via Analyzers.\n-All about reducing noise in the result views.\n-Hit the little eye to hide events from the list making it possible to\n-curate views to emphasize the important things.\n-The events are still there and can be easily shown for those who want to see them.\n-Hit the big red button to show/hide the events.\n+To create a view from the Web Ui, click the *Save as view* button on the top right of the Search fiels in the Explore Tab of a sketch.\n### Heatmap\n" } ]
Python
Apache License 2.0
google/timesketch
explain what a view is
263,095
20.08.2020 06:39:10
-7,200
9e7cb9b1c56eef5d7acdb6fe8f404dfb0e5d0744
remove heatmaps
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Adding Timelines](#adding-timelines)\n- [Adding event](#adding-event)\n- [Views](#views)\n- - [Heatmap](#heatmap)\n- [Stories](#stories)\n- [Demo](#demo)\n- [Searching](#searching)\n@@ -47,12 +46,6 @@ Views are saved search queries. Those can either be created by the User, by API\nTo create a view from the Web Ui, click the *Save as view* button on the top right of the Search fiels in the Explore Tab of a sketch.\n-### Heatmap\n-\n-*This feature is currently not implemented in the Web UI*\n-\n-~~The heatmap aggregation calculates on which day of the week and at which hour events happened. This can be very useful e.g. when analyzing lateral movement or login events.~~\n-\n### Stories\nA story is a place where you can capture the narrative of your technical investigation and add detail to your story with raw timeline data and aggregated data.\n" } ]
Python
Apache License 2.0
google/timesketch
remove heatmaps
263,095
20.08.2020 06:55:23
-7,200
81e4ba8a032349662a9d9e29fd2ab7941484f9f2
explain aggregations
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Table of Contents](#table-of-contents)\n- [Concepts](#concepts)\n+- [Login](#login)\n- [Sketches](#sketches)\n- [Adding Timelines](#adding-timelines)\n- [Adding event](#adding-event)\n+- [Add a comment](#add-a-comment)\n+- [Star an event](#star-an-event)\n- [Views](#views)\n+- [Insights / Aggegations](#insights--aggegations)\n+ - [Terms aggregation](#terms-aggregation)\n+ - [Filtered terms aggregation](#filtered-terms-aggregation)\n- [Stories](#stories)\n- [Demo](#demo)\n- [Searching](#searching)\nTimesketch 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+## Login\n+\n+Use the credentials provided by your Timesketch admin to log on to Timesketch or use OAuth to authenticate.\n+\n+## Sketches\nThere is a dedicated document to walk you through [Sketches](/docs/SketchOverview.md)\n-### Adding Timelines\n+\n+## Adding Timelines\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-### Adding event\n+## Adding event\nThis feature is currently not implemented in the Web UI. But you can add events using the [API client](/docs/APIClient.md).\n-### Views\n+## Add a comment\n+\n+You can comment events in your sketch. The comments are safed in your sketch, that means if you add a timeline to multiple sketches, the comments are only shown in the one sketch you made the comments.\n+\n+## Star an event\n+\n+Click the little star symbol in the Event List to star an event. Stared events can be used to filter on them and or to add all starred events in your story.\n+\n+## Views\nViews are saved search queries. Those can either be created by the User, by API or via Analyzers.\nTo create a view from the Web Ui, click the *Save as view* button on the top right of the Search fiels in the Explore Tab of a sketch.\n-### Stories\n+## Insights / Aggegations\n+\n+The *Insights* functionality in a sketch gives the opportunity to run aggregations on the events in a sketch.\n+\n+There are currently two aggregators available:\n+- Terms aggregation\n+- Filtered terms aggregation\n+\n+### Terms aggregation\n+\n+The term aggregation can be used for example to get a table view of the present data types in the sketch.\n+\n+You can choose between the following chart types:\n+\n+- circlechart\n+- table\n+- barchart\n+- hbchart\n+- linechart\n+\n+The next value to provide is the field you want to aggregate on, for example the data_type.\n+\n+The last value is the number of results to return.\n+\n+Once the aggregation is completed, you can save the aggregation by clicking the *save* button on the top right corner of the aggregation result, for example to add it to a story.\n+\n+### Filtered terms aggregation\n+\n+The filtered terms aggregation works the same way the terms aggregation works with one additional input field the filter query. This can be used for example to aggregate over data_types only for events that contain a certain string.\n+\n+## Stories\nA story is a place where you can capture the narrative of your technical investigation and add detail to your story with raw timeline data and aggregated data.\nThe editor lets you to write and capture the story behind your investigation and at the same time enable you to share detailed findings without spending hours writing reports.\n@@ -66,8 +115,6 @@ If you want to export a story, export the whole Sketch. The zip file will contai\nTo play with timesketch without any installation visit [demo.timesketch.org](https://demo.timesketch.org)\n-\n-\n## Searching\nThere is a dedicated document called [SearchQueryGuide](/docs/SearchQueryGuide.md) to help you create custom searches.\n" } ]
Python
Apache License 2.0
google/timesketch
explain aggregations
263,095
20.08.2020 07:00:44
-7,200
98300ba5dd92fa72521c5e1ee399fa835480c3f3
explain customize columns
[ { "change_type": "MODIFY", "old_path": "docs/Users-Guide.md", "new_path": "docs/Users-Guide.md", "diff": "- [Insights / Aggegations](#insights--aggegations)\n- [Terms aggregation](#terms-aggregation)\n- [Filtered terms aggregation](#filtered-terms-aggregation)\n+- [Customize columns](#customize-columns)\n- [Stories](#stories)\n- [Demo](#demo)\n- [Searching](#searching)\n@@ -95,6 +96,12 @@ Once the aggregation is completed, you can save the aggregation by clicking the\nThe filtered terms aggregation works the same way the terms aggregation works with one additional input field the filter query. This can be used for example to aggregate over data_types only for events that contain a certain string.\n+## Customize columns\n+\n+In the Explore view of a sketch the message is the only column visible. To add more columns, click the *customize* columns* button on the top right of the events list.\n+\n+The list of available columns is pre-populated from the columns in your timeline.\n+\n## Stories\nA story is a place where you can capture the narrative of your technical investigation and add detail to your story with raw timeline data and aggregated data.\n" } ]
Python
Apache License 2.0
google/timesketch
explain customize columns
263,095
20.08.2020 15:40:43
-7,200
351b85dc197a87049353abf78fda510c1329b832
some linter and mention analyzer_run.py
[ { "change_type": "MODIFY", "old_path": "docs/UseSigmaAnalyzer.md", "new_path": "docs/UseSigmaAnalyzer.md", "diff": "@@ -14,26 +14,28 @@ Timesketch deliberatly does not provide a set of Sigma rules, as those would add\nInstead we recommend to clone https://github.com/Neo23x0/sigma to /data/sigma.\nThis directory will not be catched by git.\n-\n-```\n+```shell\ncd data\ngit clone https://github.com/Neo23x0/sigma\n```\nThe rules then will be under\n-```\n+\n+```shell\ntimesketch/data/sigma\n```\n### Sigma Rules\nThe windows rules are stored in\n-```\n+\n+```shell\ntimesketch/data/sigma/rules/windows\n```\nThe linux rules are stored in\n-```\n+\n+```shell\ntimesketch/data/linux\ntimesketch/data/sigma/rules/linux\n```\n@@ -41,7 +43,8 @@ timesketch/data/sigma/rules/linux\n### Sigma config\nIn the config file\n-```\n+\n+```shell\nsigma_config.yaml\n```\n@@ -49,6 +52,7 @@ There is a section with mappings, most mappings where copied from HELK configura\nIf you find a mapping missing, feel free to add and create a PR.\n### Field Mapping\n+\nSome adjustments verified:\n- s/EventID/event_identifier\n@@ -57,7 +61,8 @@ Some adjustments verified:\n## Adding a new Operating System to support Sigma TS\nTo adda new operating system or new set of rules, adjust the following file:\n-```\n+\n+```shell\ntimesketch/timesketch/analyzers/sigma_tagger.py\n```\n@@ -68,7 +73,8 @@ In that file, specify, where your rules are stored and how they should appear in\nThere is a folder in the data directory that has .gitignore content for createing new rules locally.\nFolder:\n-```\n+\n+```shell\ntimesketch/data/test_rules\n```\n@@ -91,24 +97,28 @@ as well as Timesketch operator side. The analyst might not be able to see\nthe logs and the errors might only occur when running the analyzer.\nThis is why a standalone tool can be used from:\n-```\n+\n+```shell\ntest_tools/sigma_verify_rules.py\n```\nThis tool takes the following options:\n-```\n+\n+```shell\nusage: sigma_verify_rules.py [-h] [--config_file PATH_TO_TEST_FILE]\nPATH_TO_RULES\nsigma_verify_rules.py: error: the following arguments are required: PATH_TO_RULES\n```\nAnd could be used like the following to verify your rules would work:\n-```\n+\n+```shell\nsigma_verify_rules.py --config_file ../data/sigma_config.yaml ../data/sigma/rules\n```\nIf any rules in that folder is causing problems it will be shown:\n-```\n+\n+```shell\nsigma_verify_rules.py --config_file ../data/sigma_config.yaml ../timesketch/data/sigma/rules\nERROR:root:reverse_shell.yaml Error generating rule in file ../timesketch/data/sigma/rules/linux/reverse_shell.yaml you should not use this rule in Timesketch: No condition found\nERROR:root:recon_commands.yaml Error generating rule in file ../timesketch/data/sigma/rules/data/linux/recon_commands.yaml you should not use this rule in Timesketch: No condition found\n@@ -116,4 +126,3 @@ You should NOT import the following rules\n../timesketch/data/sigma/rules/linux/reverse_shell.yaml\n../timesketch/data/sigma/rules/linux/recon_commands.yaml\n```\n-\n" } ]
Python
Apache License 2.0
google/timesketch
some linter and mention analyzer_run.py
263,095
24.08.2020 16:58:59
-7,200
e67b0ef1a3d434504a63cc858e20cf3c9e3d793e
remove OS explanation
[ { "change_type": "MODIFY", "old_path": "docs/UseSigmaAnalyzer.md", "new_path": "docs/UseSigmaAnalyzer.md", "diff": "@@ -58,30 +58,6 @@ Some adjustments verified:\n- s/EventID/event_identifier\n- s/Source/source_name\n-## Adding a new Operating System to support Sigma TS\n-\n-To adda new operating system or new set of rules, adjust the following file:\n-\n-```shell\n-timesketch/timesketch/analyzers/sigma_tagger.py\n-```\n-\n-In that file, specify, where your rules are stored and how they should appear in the Timesketch UI.\n-\n-## Testing new rules\n-\n-There is a folder in the data directory that has .gitignore content for createing new rules locally.\n-\n-Folder:\n-\n-```shell\n-timesketch/data/test_rules\n-```\n-\n-Which will show up in Timesketch UI as *a_sigma_test* on top of the analyzers.\n-\n-Note: if you create new rules, you need to restart your celery worker to pick them up.\n-\n### Analyzer_run.py\nYou can run the Sigma analyzer providing sample data:\n" } ]
Python
Apache License 2.0
google/timesketch
remove OS explanation
263,095
24.08.2020 17:13:47
-7,200
6beb3d311805b6060541a05f05986be86eb52d76
change logging setup
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -31,6 +31,7 @@ import sigma.configuration as sigma_configuration\nfrom sigma.backends import elasticsearch as sigma_elasticsearch\nfrom sigma.parser import collection as sigma_collection\n+logger = logging.getLogger('timesketch.test_tool.sigma-verify')\nlogging.basicConfig(level=os.environ.get('LOGLEVEL', 'ERROR'))\ndef get_codepath():\n@@ -63,7 +64,7 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\nfalse: rule_file_path does not contain a valid sigma rule\n\"\"\"\n- logging.debug('[sigma] Reading rules from {0:s}'.format(\n+ logger.debug('[sigma] Reading rules from {0:s}'.format(\nrule_file_path))\ntry:\n@@ -76,18 +77,18 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\nrule_file_content, sigma_config, None)\nparsed_sigma_rules = parser.generate(sigma_backend)\nexcept (NotImplementedError) as e:\n- logging.error(\n+ logger.error(\n'{0:s} Error with file {1:s}: {2!s}'.format\n(rule_filename, rule_file_path, e))\nreturn False\nexcept (sigma.parser.exceptions.SigmaParseError, TypeError) as e:\n- logging.error(\n+ logger.error(\n'{0:s} Error with file {1:s} '\n'you should not use this rule in Timesketch: {2!s}'\n.format(rule_filename, rule_file_path, e))\nreturn False\nexcept (FileNotFoundError) as e:\n- logging.error(\"Rule file not found\")\n+ logger.error(\"Rule file not found\")\nreturn False\nreturn True\n@@ -140,7 +141,7 @@ def run_verifier(rules_path, config_file_path):\n# If a sub dir is found, skip it\nif os.path.isdir(os.path.join(rules_path, rule_filename)):\n- logging.debug(\n+ logger.debug(\n'Directory found, skipping: {0:s}'.format(rule_filename))\ncontinue\n@@ -150,7 +151,7 @@ def run_verifier(rules_path, config_file_path):\nif verify_rules_file(rule_file_path, sigma_config, sigma_backend):\nreturn_verified_rules.append(rule_file_path)\nelse:\n- logging.info('File did not work{0:s}'.format(rule_file_path))\n+ logger.info('File did not work{0:s}'.format(rule_file_path))\nreturn_rules_with_problems.append(rule_file_path)\nreturn return_verified_rules, return_rules_with_problems\n@@ -191,10 +192,10 @@ if __name__ == '__main__':\nsys.exit(1)\nif options.debug:\n- logging.getLogger().setLevel(logging.DEBUG)\n+ logger.setLevel(logging.DEBUG)\nif options.info:\n- logging.getLogger().setLevel(logging.INFO)\n+ logger.setLevel(logging.INFO)\nif not os.path.isfile(options.config_file_path):\nprint('Config file not found.')\n" } ]
Python
Apache License 2.0
google/timesketch
change logging setup
263,095
24.08.2020 17:22:01
-7,200
ffd37ce2a9904b9372d88573e0f4972dfe288e71
remove empty line after function docstring
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -63,7 +63,6 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\ntrue: rule_file_path contains a valid sigma rule\nfalse: rule_file_path does not contain a valid sigma rule\n\"\"\"\n-\nlogger.debug('[sigma] Reading rules from {0:s}'.format(\nrule_file_path))\n@@ -76,7 +75,7 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\nparser = sigma_collection.SigmaCollectionParser(\nrule_file_content, sigma_config, None)\nparsed_sigma_rules = parser.generate(sigma_backend)\n- except (NotImplementedError):\n+ except NotImplementedError:\nlogger.error('{0:s} Error with file {1:s}'\n.format(rule_filename, rule_file_path), exc_info=True)\nreturn False\n@@ -86,7 +85,7 @@ def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\n'you should not use this rule in Timesketch '\n.format(rule_filename, rule_file_path), exc_info=True)\nreturn False\n- except (FileNotFoundError) as e:\n+ except FileNotFoundError:\nlogger.error('Rule file not found')\nreturn False\n@@ -109,7 +108,6 @@ def run_verifier(rules_path, config_file_path):\n- sigma_verified_rules with rules that can be added\n- sigma_rules_with_problems with rules that should not be added\n\"\"\"\n-\nif not os.path.isdir(rules_path):\nraise IOError('Rules not found at path: {0:s}'.format(\nrules_path))\n" } ]
Python
Apache License 2.0
google/timesketch
remove empty line after function docstring
263,095
24.08.2020 17:24:59
-7,200
ee207f3d796e696689c0b3cad9814da538d6eb73
catch uppercase in deprecated
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -127,7 +127,7 @@ def run_verifier(rules_path, config_file_path):\nfor dirpath, dirnames, files in os.walk(rules_path):\n- if 'deprecated' in dirnames:\n+ if 'deprecated' in [x.lower for x in dirnames]:\ndirnames.remove('deprecated')\nrule_extensions = ('yml', 'yaml')\n" } ]
Python
Apache License 2.0
google/timesketch
catch uppercase in deprecated
263,095
24.08.2020 17:27:54
-7,200
55720096d545ec47cf8b3a32117078aeec1949aa
move the RULE_EXTENSIONS outside of the loop
[ { "change_type": "MODIFY", "old_path": "test_tools/sigma_verify_rules.py", "new_path": "test_tools/sigma_verify_rules.py", "diff": "@@ -34,6 +34,8 @@ from sigma.parser import collection as sigma_collection\nlogger = logging.getLogger('timesketch.test_tool.sigma-verify')\nlogging.basicConfig(level=os.environ.get('LOGLEVEL', 'ERROR'))\n+RULE_EXTENSIONS = ('yml', 'yaml')\n+\ndef get_codepath():\n\"\"\"Return the absolute path to where the tool is run from.\"\"\"\n# TODO: move this function to a library as it is duplicate to WebUI\n@@ -130,10 +132,8 @@ def run_verifier(rules_path, config_file_path):\nif 'deprecated' in [x.lower for x in dirnames]:\ndirnames.remove('deprecated')\n- rule_extensions = ('yml', 'yaml')\n-\nfor rule_filename in files:\n- if not rule_filename.lower().endswith(rule_extensions):\n+ if not rule_filename.lower().endswith(RULE_EXTENSIONS):\ncontinue\n# If a sub dir is found, skip it\n" } ]
Python
Apache License 2.0
google/timesketch
move the RULE_EXTENSIONS outside of the loop
263,133
25.08.2020 13:57:07
0
4d7d83550d81ee3fc21cb7ad56cd80898583feb9
Minor fixes in chain, making it possible for analyzers to aggregate in a specific index, changing browser analyzers to act only on a single index
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/aggregation.py", "new_path": "timesketch/api/v1/resources/aggregation.py", "diff": "@@ -390,6 +390,7 @@ class AggregationExploreResource(resources.ResourceMixin, Resource):\nfor t in sketch.timelines\nif t.get_status.status.lower() == 'ready'\n}\n+ indices_string = ','.join(sketch_indices)\naggregation_dsl = form.aggregation_dsl.data\naggregator_name = form.aggregator_name.data\n@@ -407,7 +408,9 @@ class AggregationExploreResource(resources.ResourceMixin, Resource):\nreturn {}\nif not aggregator_parameters:\naggregator_parameters = {}\n- aggregator = agg_class(sketch_id=sketch_id)\n+\n+ index = aggregator_parameters.pop('index', indices_string)\n+ aggregator = agg_class(sketch_id=sketch_id, index=index)\nchart_type = aggregator_parameters.pop('supported_charts', None)\nchart_color = aggregator_parameters.pop('chart_color', '')\nchart_title = aggregator_parameters.pop(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_search.py", "new_path": "timesketch/lib/analyzers/browser_search.py", "diff": "@@ -228,37 +228,45 @@ class BrowserSearchSketchPlugin(interface.BaseSketchAnalyzer):\nview_name='Browser Search', analyzer_name=self.NAME,\nquery_string='tag:\"browser-search\"',\nadditional_fields=self._FIELDS_TO_INCLUDE)\n+\nparams = {\n'field': 'search_string',\n'limit': 20,\n+ 'index': self.index_name,\n}\nagg_obj = self.sketch.add_aggregation(\n- name='Top 20 browser search queries', agg_name='field_bucket',\n- agg_params=params, view_id=view.id, chart_type='hbarchart',\n+ name='Top 20 browser search queries ({0:s})'.format(\n+ self.timeline_name),\n+ agg_name='field_bucket', agg_params=params, view_id=view.id,\n+ chart_type='table',\ndescription='Created by the browser search analyzer')\nparams = {\n'field': 'search_day',\n+ 'index': self.index_name,\n'limit': 20,\n}\nagg_days = self.sketch.add_aggregation(\n- name='Top 20 days of search queries', agg_name='field_bucket',\n- agg_params=params, chart_type='hbarchart',\n+ name='Top 20 days of search queries ({0:s})'.format(\n+ self.timeline_name), agg_name='field_bucket',\n+ agg_params=params, chart_type='table',\ndescription='Created by the browser search analyzer',\nlabel='informational')\nparams = {\n'query_string': 'tag:\"browser-search\"',\n+ 'index': self.index_name,\n'field': 'domain',\n}\nagg_engines = self.sketch.add_aggregation(\n- name='Top Search Engines', agg_name='query_bucket',\n- agg_params=params, view_id=view.id, chart_type='hbarchart',\n+ name='Top Search Engines ({0:s})'.format(self.timeline_name),\n+ agg_name='query_bucket', agg_params=params, view_id=view.id,\n+ chart_type='hbarchart',\ndescription='Created by the browser search analyzer')\n- story = self.sketch.add_story(utils.BROWSER_STORY_TITLE)\n- story.add_text(\n- utils.BROWSER_STORY_HEADER, skip_if_exists=True)\n+ story = self.sketch.add_story('{0:s} - {1:s}'.format(\n+ utils.BROWSER_STORY_TITLE, self.timeline_name))\n+ story.add_text(utils.BROWSER_STORY_HEADER, skip_if_exists=True)\nstory.add_text(\n'## Browser Search Analyzer.\\n\\nThe browser search '\n@@ -266,7 +274,9 @@ class BrowserSearchSketchPlugin(interface.BaseSketchAnalyzer):\n'search queries and extracts the search string.'\n'In this timeline the analyzer discovered {0:d} '\n'browser searches.\\n\\nThis is a summary of '\n- 'it\\'s findings.'.format(simple_counter))\n+ 'it\\'s findings for the timeline **{1:s}**.'.format(\n+ simple_counter, self.timeline_name))\n+\nstory.add_text(\n'The top 20 most commonly discovered searches were:')\nstory.add_aggregation(agg_obj)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_timeframe.py", "new_path": "timesketch/lib/analyzers/browser_timeframe.py", "diff": "@@ -226,7 +226,8 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\ntagged_events, _ = data_frame_outside.shape\nif tagged_events:\n- story = self.sketch.add_story(utils.BROWSER_STORY_TITLE)\n+ story = self.sketch.add_story('{0:s} - {1:s}'.format(\n+ utils.BROWSER_STORY_TITLE, self.timeline_name))\nstory.add_text(\nutils.BROWSER_STORY_HEADER, skip_if_exists=True)\n@@ -252,20 +253,20 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\n'## Browser Timeframe Analyzer\\n\\nThe browser timeframe '\n'analyzer discovered {0:d} browser events that ocurred '\n'outside of the typical browsing window of this browser '\n- 'history, or around {1:0.2f}% of the {2:d} total events.'\n- '\\n\\nThe analyzer determines the activity hours by finding '\n- 'the frequency of browsing events per hour, and then '\n+ 'history ({1:s}), or around {2:0.2f}% of the {3:d} total '\n+ 'events.\\n\\nThe analyzer determines the activity hours by '\n+ 'finding the frequency of browsing events per hour, and then '\n'discovering the longest block of most active hours before '\n'proceeding with flagging all events outside of that time '\n'period. This information can be used by other analyzers '\n'or by manually looking for other activity within the '\n'inactive time period to find unusual actions.\\n\\n'\n'The hours considered to be active hours are the hours '\n- 'between {3:02d} and {4:02d} (hours in UTC) and the '\n+ 'between {4:02d} and {5:02d} (hours in UTC) and the '\n'threshold used to determine if an hour was considered to be '\n- 'active was: {5:0.2f}.'.format(\n- tagged_events, percent, total_count, first, last,\n- threshold))\n+ 'active was: {6:0.2f}.'.format(\n+ tagged_events, self.timeline_name, percent, total_count,\n+ first, last, threshold))\ngroup = self.sketch.add_aggregation_group(\nname='Browser Activity Per Hour',\n@@ -274,12 +275,14 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\nparams = {\n'data': aggregation.to_dict(orient='records'),\n- 'title': 'Browser Activity Per Hour',\n+ 'title': 'Browser Activity Per Hour ({0:s})'.format(\n+ self.timeline_name),\n'field': 'hour',\n'order_field': 'hour',\n}\nagg_obj = self.sketch.add_aggregation(\n- name='Browser Activity Per Hour', agg_name='manual_feed',\n+ name='Browser Activity Per Hour ({0:s})'.format(\n+ self.timeline_name), agg_name='manual_feed',\nagg_params=params, chart_type='barchart',\ndescription='Created by the browser timeframe analyzer',\nlabel='informational')\n@@ -288,13 +291,15 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\nlines = [{'hour': x, 'count': threshold} for x in range(0, 24)]\nparams = {\n'data': lines,\n- 'title': 'Browser Timeframe Threshold',\n+ 'title': 'Browser Timeframe Threshold ({0:s})'.format(\n+ self.timeline_name),\n'field': 'hour',\n'order_field': 'hour',\n'chart_color': 'red',\n}\nagg_line = self.sketch.add_aggregation(\n- name='Browser Activity Per Hour', agg_name='manual_feed',\n+ name='Browser Activity Per Hour ({0:s})'.format(\n+ self.timeline_name), agg_name='manual_feed',\nagg_params=params, chart_type='linechart',\ndescription='Created by the browser timeframe analyzer',\nlabel='informational')\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain.py", "new_path": "timesketch/lib/analyzers/chain.py", "diff": "@@ -81,12 +81,16 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\nnumber_chained_events = chain_plugin.build_chain(\nbase_event=event, chain_id=chain_id)\n+ if not number_chained_events:\n+ continue\n+\ncounter[chain_id] = number_chained_events\ncounter['total'] += number_chained_events\nchain_id_list = event.source.get('chain_id_list', [])\nchain_id_list.append(chain_id)\nchain_plugins_list = event.source.get('chain_plugins', [])\n+ if chain_plugin.NAME not in chain_plugins_list:\nchain_plugins_list.append(chain_plugin.NAME)\nattributes = {\n'chain_id_list': chain_id_list,\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": "@@ -45,11 +45,11 @@ class WinPrefetchChainPlugin(interface.BaseChainPlugin):\nreturn\nyield # pylint: disable=W0101\n- search_query = 'url:\"*{0:s}\"'.format(target)\n+ search_query = 'url:\"*{0:s}*\"'.format(target)\nreturn_fields = ['url']\nevents = self.analyzer_object.event_stream(\n- search_query, return_fields=return_fields)\n+ search_query, return_fields=return_fields, scroll=False)\nfor event in events:\nurl = event.source.get('url', '')\nif target.lower() in url.lower():\n@@ -59,7 +59,7 @@ class WinPrefetchChainPlugin(interface.BaseChainPlugin):\nreturn_fields = ['link_target']\nevents = self.analyzer_object.event_stream(\n- lnk_query, return_fields=return_fields)\n+ lnk_query, return_fields=return_fields, scroll=False)\nfor event in events:\nlink_target = event.source.get('link_target', '')\nif target.lower() in link_target.lower():\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -715,7 +715,7 @@ class BaseIndexAnalyzer(object):\ndef event_stream(\nself, query_string=None, query_filter=None, query_dsl=None,\n- indices=None, return_fields=None):\n+ indices=None, return_fields=None, scroll=True):\n\"\"\"Search ElasticSearch.\nArgs:\n@@ -724,6 +724,8 @@ class BaseIndexAnalyzer(object):\nquery_dsl: Dictionary containing Elasticsearch DSL query.\nindices: List of indices to query.\nreturn_fields: List of fields to return.\n+ scroll: Boolean determining whether we support scrolling searches\n+ or not. Defaults to True.\nReturns:\nGenerator of Event objects.\n@@ -758,7 +760,8 @@ class BaseIndexAnalyzer(object):\nquery_filter=query_filter,\nquery_dsl=query_dsl,\nindices=indices,\n- return_fields=return_fields\n+ return_fields=return_fields,\n+ enable_scroll=scroll,\n)\nfor event in event_generator:\nyield Event(event, self.datastore, sketch=self.sketch)\n" } ]
Python
Apache License 2.0
google/timesketch
Minor fixes in chain, making it possible for analyzers to aggregate in a specific index, changing browser analyzers to act only on a single index
263,133
26.08.2020 13:22:20
0
d1bca77f40f537597ca6858c31bfab85e3b9b1e4
Adding the chrome download chain plugin
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_plugins/__init__.py", "new_path": "timesketch/lib/analyzers/chain_plugins/__init__.py", "diff": "# -*- coding: utf-8 -*-\n\"\"\"Imports for the chain analyzer.\"\"\"\n+from timesketch.lib.analyzers.chain_plugins import chrome_download_file\nfrom timesketch.lib.analyzers.chain_plugins import win_prefetch\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/chain_plugins/chrome_download_file.py", "diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Plugin for chaining Chrome downloads to filesystem events.\"\"\"\n+\n+from timesketch.lib.analyzers.chain_plugins import interface\n+from timesketch.lib.analyzers.chain_plugins import manager\n+\n+\n+class ChromeDownloadFilesystemChainPlugin(interface.BaseChainPlugin):\n+ \"\"\"A plugin to chain Chrome downloads to filesystem events.\"\"\"\n+\n+ NAME = 'chromefilesystem'\n+ DESCRIPTION = (\n+ 'Plugin to chain Chrome download records to corresponding filesystem '\n+ 'events and even execution events.')\n+\n+ SEARCH_QUERY = 'data_type:\"chrome:history:file_downloaded\"'\n+ EVENT_FIELDS = ['full_path']\n+\n+ def get_chained_events(self, base_event):\n+ \"\"\"Yields an event that is chained or linked to the base event.\n+\n+ Args:\n+ base_event: the base event of the chain, used to construct further\n+ queries (instance of Event).\n+\n+ Yields:\n+ An event (instance of Event) object that is linked or chained to\n+ the base event, according to the plugin.\n+ \"\"\"\n+ target = base_event.source.get('full_path', '')\n+ if not target:\n+ return\n+ yield # pylint: disable=W0101\n+\n+ if '\\\\' in target:\n+ separator = '\\\\'\n+ else:\n+ separator = '/'\n+\n+ target = target.split(separator)[-1]\n+ search_query = (\n+ '(data_type:\"fs:stat\" AND filename:\"*{0:s}\") OR '\n+ '(data_type:\"fs:stat:ntfs\" AND name:\"{0:s}\")').format(\n+ target)\n+ return_fields = ['filename', 'path_hints']\n+\n+ events = self.analyzer_object.event_stream(\n+ search_query, return_fields=return_fields, scroll=False)\n+ for event in events:\n+ yield event\n+\n+ exec_query = 'executable:\"*{0:s}\"'.format(target)\n+ return_fields = ['executable']\n+\n+ events = self.analyzer_object.event_stream(\n+ exec_query, return_fields=return_fields, scroll=False)\n+ for event in events:\n+ yield event\n+\n+\n+manager.ChainPluginsManager.register_plugin(ChromeDownloadFilesystemChainPlugin)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/testlib.py", "new_path": "timesketch/lib/testlib.py", "diff": "@@ -247,7 +247,7 @@ class MockDataStore(object):\n# pylint: disable=unused-argument\ndef search_stream(self, query_string, query_filter, query_dsl,\n- indices, return_fields):\n+ indices, return_fields, enable_scroll=True):\nfor i in range(len(self.event_store)):\nyield self.event_store[str(i)]\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the chrome download chain plugin
263,133
27.08.2020 09:54:06
0
c80e57ab5e8b17b7ec8aed9abffd96df6c842afc
Making changes to chain analyzer as well as changing tag behavior in importing.
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/export.py", "new_path": "timesketch/api/v1/export.py", "diff": "@@ -207,6 +207,9 @@ def query_results_to_dataframe(result, sketch):\nline['_id'] = event['_id']\nline['_type'] = event['_type']\nline['_index'] = event['_index']\n+ if 'tag' in line:\n+ if isinstance(line['tag'], (list, tuple)):\n+ line['tag'] = ','.join(line['tag'])\ntry:\nfor label in line['timesketch_label']:\nif sketch.id != label['sketch_id']:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain.py", "new_path": "timesketch/lib/analyzers/chain.py", "diff": "@@ -54,7 +54,9 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\nlink_emoji = emojis.get_emoji('LINK')\nnumber_of_base_events = 0\n+ number_of_chains = 0\ncounter = collections.Counter()\n+ events_to_update = {}\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@@ -68,7 +70,6 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\nsearch_string = chain_plugin.SEARCH_QUERY\nreturn_fields = chain_plugin.EVENT_FIELDS\n- return_fields.extend(['chain_id_list', 'chain_plugins'])\nevents = self.event_stream(\nquery_string=search_string, query_dsl=search_dsl,\nreturn_fields=return_fields)\n@@ -76,35 +77,62 @@ class ChainSketchPlugin(interface.BaseSketchAnalyzer):\nfor event in events:\nif not chain_plugin.process_chain(event):\ncontinue\n- number_of_base_events += 1\nchain_id = uuid.uuid4().hex\n- number_chained_events = chain_plugin.build_chain(\n+ chained_events = chain_plugin.build_chain(\nbase_event=event, chain_id=chain_id)\n+ number_chained_events = len(chained_events)\nif not number_chained_events:\ncontinue\n- counter[chain_id] = number_chained_events\n+ for chained_event in chained_events:\n+ chained_id = chained_event.get('event_id')\n+ if chained_id not in events_to_update:\n+ default = {\n+ 'event': chained_event.get('event'),\n+ 'chains': []\n+ }\n+ events_to_update[chained_id] = default\n+\n+ events_to_update[chained_id]['chains'].append(\n+ chained_event.get('chain'))\n+\n+ number_of_base_events += 1\n+\n+ counter[chain_plugin.NAME] += number_chained_events\ncounter['total'] += number_chained_events\n- chain_id_list = event.source.get('chain_id_list', [])\n- chain_id_list.append(chain_id)\n- chain_plugins_list = event.source.get('chain_plugins', [])\n- if chain_plugin.NAME not in chain_plugins_list:\n- chain_plugins_list.append(chain_plugin.NAME)\n+ chain = {\n+ 'chain_id': chain_id,\n+ 'plugin': chain_plugin.NAME,\n+ 'is_base': True,\n+ 'leafs': number_chained_events,\n+ }\n+ if event.event_id not in events_to_update:\n+ default = {\n+ 'event': event,\n+ 'chains': []\n+ }\n+ events_to_update[event.event_id] = default\n+ events_to_update[event.event_id]['chains'].append(chain)\n+ number_of_chains += 1\n+\n+ for event_update in events_to_update.values():\n+ event = event_update.get('event')\nattributes = {\n- 'chain_id_list': chain_id_list,\n- 'chain_plugins': chain_plugins_list}\n+ 'chains': event_update.get('chains')\n+ }\nevent.add_attributes(attributes)\nevent.add_emojis([link_emoji])\nevent.commit()\n- number_of_chains = len(counter.keys()) - 1\n+ chain_string = ' - '.join([\n+ '[{0:s}] {1:d}'.format(x[0], x[1]) for x in counter.most_common()])\nreturn (\n'{0:d} base events annotated with a chain UUID for {1:d} '\n- 'chains for a total of {2:d} events.'.format(\n+ 'chains for a total of {2:d} events. {3:s}'.format(\nnumber_of_base_events, number_of_chains,\n- counter['total']))\n+ counter['total'], chain_string))\nmanager.AnalysisManager.register_analyzer(ChainSketchPlugin)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_plugins/chrome_download_file.py", "new_path": "timesketch/lib/analyzers/chain_plugins/chrome_download_file.py", "diff": "@@ -50,7 +50,7 @@ class ChromeDownloadFilesystemChainPlugin(interface.BaseChainPlugin):\nyield event\nexec_query = 'executable:\"*{0:s}\"'.format(target)\n- return_fields = ['executable']\n+ return_fields = ['executable', 'chains']\nevents = self.analyzer_object.event_stream(\nexec_query, return_fields=return_fields, scroll=False)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_plugins/interface.py", "new_path": "timesketch/lib/analyzers/chain_plugins/interface.py", "diff": "@@ -49,7 +49,7 @@ class BaseChainPlugin(object):\nreturn True\ndef build_chain(self, base_event, chain_id):\n- \"\"\"Build chain from base event.\n+ \"\"\"Returns a chain of events from a base event.\nArgs:\nbase_event: the base event of the chain, used to construct further\n@@ -57,24 +57,21 @@ class BaseChainPlugin(object):\nchain_id: a string with the chain UUID value.\nReturns:\n- An integer with the total number of discovered events.\n+ A list of dicts with the chain and event attached.\n\"\"\"\n- total_events = 0\n+ events = []\nfor event in self.get_chained_events(base_event):\n- chain_id_list = event.source.get('chain_id_list', [])\n- chain_id_list.append(chain_id)\n- chain_plugins = event.source.get('chain_plugins', [])\n- chain_plugins.append(self.NAME)\n-\n- attributes = {\n- 'chain_id_list': chain_id_list,\n- 'chain_plugins': chain_plugins}\n-\n- event.add_attributes(attributes)\n- event.add_emojis(self._EMOJIS)\n- event.commit()\n- total_events += 1\n- return total_events\n+ chain = {\n+ 'chain_id': chain_id,\n+ 'plugin': self.NAME,\n+ 'is_base': False\n+ }\n+ events.append({\n+ 'event_id': event.event_id,\n+ 'event': event,\n+ 'chain': chain,\n+ })\n+ return events\n@abc.abstractmethod\ndef get_chained_events(self, base_event):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/utils.py", "new_path": "timesketch/lib/utils.py", "diff": "@@ -53,6 +53,26 @@ def random_color():\nreturn '{0:02X}{1:02X}{2:02X}'.format(rgb[0], rgb[1], rgb[2])\n+def _parse_tag_field(row):\n+ \"\"\"Reading in a tag field and converting to a list of strings.\"\"\"\n+ if isinstance(row, (list, tuple)):\n+ return row\n+\n+ if not isinstance(row, str):\n+ row = str(row)\n+\n+ if row.startswith('[') and row.endswith(']'):\n+ return json.loads(row)\n+\n+ if row == '-':\n+ return []\n+\n+ if ',' in row:\n+ return row.split(',')\n+\n+ return [row]\n+\n+\ndef read_and_validate_csv(file_handle, delimiter=','):\n\"\"\"Generator for reading a CSV file.\n@@ -97,6 +117,8 @@ def read_and_validate_csv(file_handle, delimiter=','):\ntime.mktime(parsed_datetime.utctimetuple()) * 1000000)\nnormalized_timestamp += parsed_datetime.microsecond\nrow['timestamp'] = str(normalized_timestamp)\n+ if 'tag' in row:\n+ row['tag'] = [x for x in _parse_tag_field(row['tag']) if x]\nexcept ValueError:\ncontinue\n@@ -185,6 +207,9 @@ def read_and_validate_jsonl(file_handle):\n'Missing field(s) at line {0:n}: {1:s}'.format(\nlineno, ','.join(missing_fields)))\n+ if 'tag' in linedict:\n+ linedict['tag'] = [\n+ x for x in _parse_tag_field(linedict['tag']) if x]\nyield linedict\nexcept ValueError as e:\n" } ]
Python
Apache License 2.0
google/timesketch
Making changes to chain analyzer as well as changing tag behavior in importing.
263,133
27.08.2020 11:32:40
0
15e80218c32e3362da11c193091aa573a4181bfe
Minor linter
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/chain_test.py", "new_path": "timesketch/lib/analyzers/chain_test.py", "diff": "\"\"\"Tests for Chain analyzer.\"\"\"\nfrom __future__ import unicode_literals\n-import mock\nimport uuid\n+import mock\n+\nfrom timesketch.lib import emojis\nfrom timesketch.lib import testlib\n@@ -36,7 +37,7 @@ class FakeAnalyzer(chain.ChainSketchPlugin):\n\"\"\"Fake analyzer object used for \"finding events\".\"\"\"\ndef event_stream(self, query_string=None, query_filter=None, query_dsl=None,\n- indices=None, return_fields=None):\n+ indices=None, return_fields=None, scroll=True):\n\"\"\"Yields few test events.\"\"\"\nevent_one = FakeEvent({\n'url': 'http://minsida.biz',\n@@ -135,8 +136,8 @@ class TestChainAnalyzer(testlib.BaseTest):\nfor event in plugin.ALL_EVENTS:\nattributes = event.attributes\nchains = attributes.get('chains', [])\n- for chain in chains:\n- plugin = chain.get('plugin', '')\n+ for event_chain in chains:\n+ plugin = event_chain.get('plugin', '')\nself.assertEqual(plugin, 'fake_chain')\nevent_emojis = event.emojis\n" } ]
Python
Apache License 2.0
google/timesketch
Minor linter
263,095
01.09.2020 11:10:47
-7,200
0f882cc6713f60c36883f8b1ca78b009817ddab0
refactor some variable naming
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/sigma_tagger.py", "new_path": "timesketch/lib/analyzers/sigma_tagger.py", "diff": "@@ -56,14 +56,14 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nint: number of events tagged.\n\"\"\"\nreturn_fields = []\n- tagged_events = 0\n+ tagged_events_counter = 0\nevents = self.event_stream(\nquery_string=query, return_fields=return_fields)\nfor event in events:\nevent.add_tags(['sigma_{0:s}'.format(tag_name)])\nevent.commit()\n- tagged_events += 1\n- return tagged_events\n+ tagged_events_counter += 1\n+ return tagged_events_counter\ndef run(self):\n\"\"\"Entry point for the analyzer.\n@@ -75,7 +75,7 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nself.sigma_config, {})\ntags_applied = {}\n- simple_counter = 0\n+ sigma_rule_counter = 0\nrules_path = os.path.join(os.path.dirname(__file__), self._RULES_PATH)\n@@ -116,7 +116,7 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nfor sigma_rule in parsed_sigma_rules:\ntry:\n- simple_counter += 1\n+ sigma_rule_counter += 1\n# TODO Investigate how to handle .keyword\n# fields in Sigma.\n# https://github.com/google/timesketch/issues/1199#issuecomment-639475885\n@@ -125,9 +125,9 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nlogger.info(\n'[sigma] Generated query {0:s}'\n.format(sigma_rule))\n- sum_of_tagged_events = self.run_sigma_rule(\n+ tagged_events_counter = self.run_sigma_rule(\nsigma_rule, tag_name)\n- tags_applied[tag_name] += sum_of_tagged_events\n+ tags_applied[tag_name] += tagged_events_counter\nexcept elasticsearch.TransportError \\\nas es_TransportError:\nlogger.error(\n@@ -138,11 +138,11 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\ntotal_tagged_events = sum(tags_applied.values())\noutput_string = 'Applied {0:d} tags\\n'.format(total_tagged_events)\n- for tag_name, sum_of_tagged_events in tags_applied.items():\n+ for tag_name, tagged_events_counter in tags_applied.items():\noutput_string += '* {0:s}: {1:d}\\n'.format(\n- tag_name, sum_of_tagged_events)\n+ tag_name, tagged_events_counter)\n- if simple_counter > 0:\n+ if sigma_rule_counter > 0:\nview = self.sketch.add_view(\nview_name='Sigma Rule matches', analyzer_name=self.NAME,\nquery_string='tag:\"sigma*\"')\n@@ -165,7 +165,7 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\n'analyzer takes Events and matches them with Sigma rules.'\n'In this timeline the analyzer discovered {0:d} '\n'Sigma tags.\\n\\nThis is a summary of '\n- 'it\\'s findings.'.format(simple_counter))\n+ 'it\\'s findings.'.format(sigma_rule_counter))\nstory.add_text(\n'The top 20 most commonly discovered tags were:')\nstory.add_aggregation(agg_obj)\n" } ]
Python
Apache License 2.0
google/timesketch
refactor some variable naming
263,095
01.09.2020 12:19:51
-7,200
f20f95179e021996039be6bab55230f1c84b7fbe
be verbose how analyzer_run works
[ { "change_type": "MODIFY", "old_path": "docs/WriteAnalyzers.md", "new_path": "docs/WriteAnalyzers.md", "diff": "@@ -14,7 +14,8 @@ You do not have to install Timesketch or any docker for that.\nTo be able to run it, you need a python environment with some requirements\ninstalled.\n-A good guide to install a venv is published by github [here](https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/)\n+A good guide to install a venv is published by github\n+[here](https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/)\n```\npython3 analyzer_run.py\n@@ -25,7 +26,8 @@ analyzer_run.py: error: the following arguments are required: PATH_TO_ANALYZER,\n### create your sample data\nYou can create your sample data either in CSV or JSONL with the same format\n-that Timesketch can ingest. To learn more about that visit [CreateTimelineFromJSONorCSV](CreateTimelineFromJSONorCSV.md)\n+that Timesketch can ingest. To learn more about that visit\n+[CreateTimelineFromJSONorCSV](CreateTimelineFromJSONorCSV.md)\n### use existing sample data\n@@ -94,5 +96,8 @@ Result from analyzer run:\n### Remark\n-Do not try to run analyzer_run.py in your docker instance of Timesketch\n+* Do not try to run analyzer_run.py in your docker instance of Timesketch\nas it will mix certain things with the actual installed Timesketch instance.\n+\n+* Analyzer_run does not actually execute the ES query. Instead all event data\n+passed to the script are assumed to \"match\" the analyzer.\n" }, { "change_type": "MODIFY", "old_path": "test_tools/analyzer_run.py", "new_path": "test_tools/analyzer_run.py", "diff": "@@ -22,6 +22,9 @@ Example way of running the tool:\n$ python analyzer_run.py --test_file test_file.txt \\\n../timesketch/lib/analyzers/my_analyzer.py MyAnalyzerSketchPlugin\n+Remark: The tool ignores Elastic Search queries. It should be fed with\n+data that matches the expected output of the analyzer.\n+\n\"\"\"\nimport argparse\n" } ]
Python
Apache License 2.0
google/timesketch
be verbose how analyzer_run works
263,093
02.09.2020 19:51:35
-7,200
e577724d5215c2a64ef38c282ad212419ec8f671
e2e testing framework
[ { "change_type": "MODIFY", "old_path": "docker/e2e/Dockerfile", "new_path": "docker/e2e/Dockerfile", "diff": "-FROM gcr.io/timesketch-build/release/timesketch:latest\n+# Use the official Docker Hub Ubuntu 18.04 base image\n+FROM ubuntu:18.04\n+\n+# Workaround for bug in setuptools v50.\n+# Ref: https://github.com/pypa/setuptools/issues/2350\n+ENV SETUPTOOLS_USE_DISTUTILS=stdlib\n+\n+RUN apt-get update && apt-get install -y --no-install-recommends \\\n+ software-properties-common \\\n+ python3-pip \\\n+ python3-wheel \\\n+ python3-setuptools \\\n+ python3-psycopg2 \\\n+ git \\\n+ wget \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n+# Install Plaso\n+RUN add-apt-repository -y ppa:gift/stable\n+RUN apt-get update && apt-get install -y --no-install-recommends \\\n+ plaso-tools \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n+# Install Timesketch from master to get the latest code\n+RUN wget https://raw.githubusercontent.com/google/timesketch/master/requirements.txt\n+RUN pip3 install -r requirements.txt\n+RUN pip3 install https://github.com/google/timesketch/archive/master.zip\n+\n+# Install Timesketch API client\n+RUN pip3 install timesketch-api-client\n# Copy Timesketch config files into /etc/timesketch\n-ADD . /tmp/timesketch\nRUN mkdir /etc/timesketch\n-RUN cp /tmp/timesketch/data/timesketch.conf /etc/timesketch/\n-RUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\n-RUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/\n+RUN cp /usr/local/share/timesketch/timesketch.conf /etc/timesketch/\n+RUN cp /usr/local/share/timesketch/features.yaml /etc/timesketch/\n+RUN cp /usr/local/share/timesketch/sigma_config.yaml /etc/timesketch/\n# Copy the entrypoint script into the container\nCOPY docker/e2e/docker-entrypoint.sh /\nRUN chmod a+x /docker-entrypoint.sh\n-# Expose the port used by Timesketch\n-EXPOSE 5000\n-\n# Load the entrypoint script to be run later\nENTRYPOINT [\"/docker-entrypoint.sh\"]\n" }, { "change_type": "MODIFY", "old_path": "docker/e2e/docker-compose.yml", "new_path": "docker/e2e/docker-compose.yml", "diff": "@@ -10,8 +10,8 @@ services:\n- ELASTIC_PORT=9200\n- REDIS_ADDRESS=redis\n- REDIS_PORT=6379\n- - TIMESKETCH_USER=${TIMESKETCH_USER}\n- - TIMESKETCH_PASSWORD=${TIMESKETCH_PASSWORD}\n+ - TIMESKETCH_USER=test\n+ - TIMESKETCH_PASSWORD=test\nbuild:\ncontext: ../../\ndockerfile: ./docker/e2e/Dockerfile\n@@ -32,7 +32,7 @@ services:\n# uncomment the following lines to control JVM memory utilization\n# in smaller deployments with minimal resources\n# - ES_JAVA_OPTS= -Xms1g -Xmx1g # 1G min/1G max\n- image: elasticsearch:7.6.0\n+ image: elasticsearch:${ELASTICSEARCH_VERSION}\nports:\n- \"9200:9200\"\n- \"9300:9300\"\n" }, { "change_type": "MODIFY", "old_path": "docker/e2e/docker-entrypoint.sh", "new_path": "docker/e2e/docker-entrypoint.sh", "diff": "# Run the container the default way\nif [ \"$1\" = 'timesketch' ]; then\n+\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\nOPENSSL_RAND=$( openssl rand -base64 32 )\n@@ -46,7 +47,7 @@ if [ \"$1\" = 'timesketch' ]; then\nTIMESKETCH_USER=\"admin\"\necho \"TIMESKETCH_USER set to default: ${TIMESKETCH_USER}\";\nfi\n- if [ $TIMESKETCH_PASSWORD ]; then echo \"TIMESKETCH_PASSWORD usage is discouraged. Use Docker Secrets instead and set TIMESKETCH_PASSWORD_FILE to /run/secrets/secret-name\"; fi\n+\nif [ $TIMESKETCH_PASSWORD_FILE ]; then TIMESKETCH_PASSWORD=$(cat $TIMESKETCH_PASSWORD_FILE); fi\nif [ -z ${TIMESKETCH_PASSWORD:+x} ]; then\nTIMESKETCH_PASSWORD=\"$(openssl rand -base64 32)\"\n@@ -61,7 +62,7 @@ if [ \"$1\" = 'timesketch' ]; then\n# Run the Timesketch server (without SSL)\ncd /tmp\nexec `bash -c \"/usr/local/bin/celery -A timesketch.lib.tasks worker --uid nobody --loglevel info & \\\n- gunicorn -b 0.0.0.0:80 --access-logfile - --error-logfile - --log-level info --timeout 120 timesketch.wsgi:application\"`\n+ gunicorn --reload -b 0.0.0.0:80 --access-logfile - --error-logfile - --log-level info --timeout 120 timesketch.wsgi:application\"`\nfi\n# Run a custom command on container start\n" }, { "change_type": "ADD", "old_path": null, "new_path": "end_to_end_tests/__init__.py", "diff": "+from . import query_test\n" }, { "change_type": "ADD", "old_path": null, "new_path": "end_to_end_tests/interface.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import time\n+import unittest\n+import os\n+\n+from timesketch_api_client.client import TimesketchApi\n+\n+TEST_DATA_DIR = '/usr/local/src/timesketch/end_to_end_tests/test_data'\n+HOST_URI = 'http://127.0.0.1'\n+USERNAME = 'test'\n+PASSWORD = 'test'\n+\n+\n+class BaseEndToEndTest(object):\n+ \"\"\"Base class for end to end tests.\n+\n+ Attributes:\n+ name: Test name.\n+ client: Instance of an API client.\n+ sketch: Instance of Sketch object.\n+ \"\"\"\n+\n+ NAME = 'name'\n+\n+ def __init__(self):\n+ \"\"\"Initialize the analyzer object.\"\"\"\n+ self.name = self.NAME\n+ self.client = TimesketchApi(\n+ host_uri=HOST_URI, username=USERNAME, password=PASSWORD)\n+ self.sketch = self.client.create_sketch(name=self.name)\n+ self.assertions = unittest.TestCase()\n+\n+ def import_timeline(self, filename, wait=True):\n+ file_path = os.path.join(TEST_DATA_DIR, filename)\n+ print('Importing: {}'.format(file_path))\n+ timeline = self.sketch.upload(\n+ timeline_name=file_path, file_path=file_path)\n+\n+ if wait:\n+ while True:\n+ _ = timeline.lazyload_data(refresh_cache=True)\n+ status = timeline.status\n+ if status == 'ready':\n+ break\n+ time.sleep(5)\n+\n+ def run_wrapper(self):\n+ \"\"\"A wrapper method to run the test.\"\"\"\n+ print('Running tests from: {}'.format(self.name))\n+ self.run()\n+\n+ def run(self):\n+ \"\"\"Entry point for the analyzer.\"\"\"\n+ raise NotImplementedError\n" }, { "change_type": "ADD", "old_path": null, "new_path": "end_to_end_tests/manager.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"This file contains a class for managing e2e tests.\"\"\"\n+\n+\n+class EndToEndTestManager(object):\n+ \"\"\"The test manager.\"\"\"\n+\n+ _class_registry = {}\n+ _exclude_registry = set()\n+\n+ @classmethod\n+ def get_tests(cls):\n+ \"\"\"Retrieves the registered tests.\n+\n+ Yields:\n+ tuple: containing:\n+ unicode: the uniquely identifying name of the test\n+ type: the test class.\n+ \"\"\"\n+ for test_name, test_class in iter(cls._class_registry.items()):\n+ if test_name in cls._exclude_registry:\n+ continue\n+ yield test_name, test_class\n+\n+ @classmethod\n+ def get_test(cls, test_name):\n+ \"\"\"Retrieves a class object of a specific test.\n+\n+ Args:\n+ test_name (unicode): name of the test to retrieve.\n+\n+ Returns:\n+ Instance of Test class object.\n+\n+ Raises:\n+ KeyError: if the test is not registered.\n+ \"\"\"\n+ try:\n+ test_class = cls._class_registry[test_name.lower()]\n+ except KeyError:\n+ raise KeyError(\n+ 'No such chart type: {0:s}'.format(test_name.lower()))\n+ return test_class\n+\n+ @classmethod\n+ def register_test(cls, test_class, exclude_from_list=False):\n+ \"\"\"Registers an test class.\n+\n+ The test classes are identified by their lower case name.\n+\n+ Args:\n+ test_class (type): the test class to register.\n+ exclude_from_list (boolean): if set to True then the test\n+ gets registered but will not be included in the\n+ get_tests function. Defaults to False.\n+\n+ Raises:\n+ KeyError: if class is already set for the corresponding name.\n+ \"\"\"\n+ test_name = test_class.NAME.lower()\n+ if test_name in cls._class_registry:\n+ raise KeyError('Class already set for name: {0:s}.'.format(\n+ test_class.NAME))\n+ cls._class_registry[test_name] = test_class\n+ if exclude_from_list:\n+ cls._exclude_registry.add(test_name)\n+\n+ @classmethod\n+ def clear_registration(cls):\n+ \"\"\"Clears all test registrations.\"\"\"\n+ cls._class_registry = {}\n+ cls._exclude_registry = set()\n" }, { "change_type": "ADD", "old_path": null, "new_path": "end_to_end_tests/query_test.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"E2E tests of Timesketch query functionality.\"\"\"\n+\n+from . import interface\n+from . import manager\n+\n+\n+class QueryTest(interface.BaseEndToEndTest):\n+ NAME = 'query_test'\n+\n+ def __init__(self):\n+ super(QueryTest, self).__init__()\n+\n+ def run(self):\n+ self.import_timeline('evtx.plaso')\n+ response_json = self.sketch.explore(query_string=\"*\")\n+ count = response_json.get('meta', {}).get('es_total_count', 0)\n+ self.assertions.assertEqual(count, 3205)\n+\n+\n+manager.EndToEndTestManager.register_test(QueryTest)\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": "end_to_end_tests/test_data/evtx.plaso", "new_path": "end_to_end_tests/test_data/evtx.plaso", "diff": "Binary files /dev/null and b/end_to_end_tests/test_data/evtx.plaso differ\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test_tools/e2e/run_end_to_end_tests.sh", "diff": "+#!/bin/bash\n+#\n+# Script to run end-to-end tests.\n+\n+# Fail on any error\n+set -e\n+\n+# Defaults\n+DEFAULT_ELASTICSEARCH_VERSION=7.6.2\n+\n+# Set Elasticsearch version to run\n+[ -z \"$ELASTICSEARCH_VERSION\" ] && export ELASTICSEARCH_VERSION=$DEFAULT_ELASTICSEARCH_VERSION\n+\n+# Container ID for the web server\n+export CONTAINER_ID=\"$(sudo -E docker container list -f name=e2e_timesketch -q)\"\n+\n+# Start containers if necessary\n+if [ -z \"$CONTAINER_ID\" ]; then\n+ sudo -E docker-compose -f ./docker/e2e/docker-compose.yml up -d\n+ /bin/sleep 120 # Wait for all containers to be available\n+ export CONTAINER_ID=\"$(sudo -E docker container list -f name=e2e_timesketch -q)\"\n+fi\n+\n+sudo -E docker exec $CONTAINER_ID python3 /usr/local/src/timesketch/test_tools/e2e/run_in_container.py\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test_tools/e2e/run_in_container.py", "diff": "+from end_to_end_tests import manager as test_manager\n+\n+manager = test_manager.EndToEndTestManager()\n+for test in manager.get_tests():\n+ t = test[1]()\n+ t.run_wrapper()\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
e2e testing framework
263,096
03.09.2020 09:58:18
-7,200
2d3c304be4ddb961c992002bf5727247ac591f97
Update analyzer_run.py
[ { "change_type": "MODIFY", "old_path": "test_tools/analyzer_run.py", "new_path": "test_tools/analyzer_run.py", "diff": "@@ -22,7 +22,7 @@ Example way of running the tool:\n$ python analyzer_run.py --test_file test_file.txt \\\n../timesketch/lib/analyzers/my_analyzer.py MyAnalyzerSketchPlugin\n-Remark: The tool ignores Elastic Search queries. It should be fed with\n+Remark: The tool ignores Elasticsearch queries. It should be fed with\ndata that matches the expected output of the analyzer.\n\"\"\"\n" } ]
Python
Apache License 2.0
google/timesketch
Update analyzer_run.py
263,133
03.09.2020 11:03:01
0
9acd9262f88270307b6d74781aa76884a9b444d2
Minor changes to the way date is parsed when a custom event is added
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -1268,7 +1268,8 @@ class Sketch(resource.BaseResource):\nArgs:\nmessage: A string that will be used as the message string.\n- date: A string with the timestamp of the message.\n+ date: A string with the timestamp of the message. This should be\n+ in a human readable format, eg: \"2020-09-03T22:52:21\".\ntimestamp_desc : Description of the timestamp.\nattributes: A dict of extra attributes to add to the event.\ntags: A list of strings to include as tags.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/event.py", "new_path": "timesketch/api/v1/resources/event.py", "diff": "@@ -127,7 +127,15 @@ class EventCreateResource(resources.ResourceMixin, Resource):\ndate = datetime.datetime.utcnow().isoformat()\nelse:\n# derive datetime from timestamp:\n+ try:\ndate = dateutil.parser.parse(date_string)\n+ except OverflowError as e:\n+ logger.error('Unable to convert date string', exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to add event, not able to convert the date '\n+ 'string. Was it properly formed? Error: {0!s}'.format(\n+ e))\ntimestamp = int(\ntime.mktime(date.utctimetuple())) * 1000000\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to the way date is parsed when a custom event is added
263,133
03.09.2020 11:04:56
0
dc89dedc705c8da185729f77d663b184139e9437
Adding an error
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/event.py", "new_path": "timesketch/api/v1/resources/event.py", "diff": "@@ -129,7 +129,7 @@ class EventCreateResource(resources.ResourceMixin, Resource):\n# derive datetime from timestamp:\ntry:\ndate = dateutil.parser.parse(date_string)\n- except OverflowError as e:\n+ except (dateutil.parser.ParserError, OverflowError) as e:\nlogger.error('Unable to convert date string', exc_info=True)\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST,\n" } ]
Python
Apache License 2.0
google/timesketch
Adding an error
263,133
07.09.2020 13:32:27
0
839b91e1eb98e8920879d7479943a68f2b7e9e08
Adding data_type into the importer.
[ { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "@@ -46,6 +46,7 @@ class ImportStreamer(object):\n# Define default values.\nDEFAULT_TEXT_ENCODING = 'utf-8'\nDEFAULT_TIMESTAMP_DESC = 'Time Logged'\n+ DEFAULT_DATA_TYPE = 'data:entry'\ndef __init__(self):\n\"\"\"Initialize the upload streamer.\"\"\"\n@@ -65,6 +66,7 @@ class ImportStreamer(object):\nself._chunk = 1\n+ self._data_type = self.DEFAULT_DATA_TYPE\nself._text_encoding = self.DEFAULT_TEXT_ENCODING\nself._timestamp_desc = self.DEFAULT_TIMESTAMP_DESC\nself._threshold_entry = self.DEFAULT_ENTRY_THRESHOLD\n@@ -93,6 +95,7 @@ class ImportStreamer(object):\nmy_dict['message'] = format_string.format(**my_dict)\n_ = my_dict.setdefault('timestamp_desc', self._timestamp_desc)\n+ _ = my_dict.setdefault('data_type', self._data_type)\nif 'datetime' not in my_dict:\ndate = ''\n@@ -141,6 +144,9 @@ class ImportStreamer(object):\nif 'timestamp_desc' not in data_frame:\ndata_frame['timestamp_desc'] = self._timestamp_desc\n+ if 'data_type' not in data_frame:\n+ data_frame['data_type'] = self._data_type\n+\nif 'datetime' not in data_frame:\nif self._datetime_field and self._datetime_field in data_frame:\ntry:\n@@ -593,6 +599,10 @@ class ImportStreamer(object):\n\"\"\"Set the CSV delimiter for CSV file parsing.\"\"\"\nself._csv_delimiter = delimiter\n+ def set_data_type(self, data_type):\n+ \"\"\"Sets the column where the data_type is defined in.\"\"\"\n+ self._data_type = data_type\n+\ndef set_datetime_column(self, column):\n\"\"\"Sets the column where the timestamp is defined in.\"\"\"\nself._datetime_field = column\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/version.py", "new_path": "importer_client/python/timesketch_import_client/version.py", "diff": "# limitations under the License.\n\"\"\"Version information for Timesketch Import Client.\"\"\"\n-__version__ = '20200709'\n+__version__ = '20200907'\ndef get_version():\n" } ]
Python
Apache License 2.0
google/timesketch
Adding data_type into the importer.
263,133
07.09.2020 14:02:52
0
2a23202d62dc40d7274262099e3a7386e010fcb0
Making the data_type more explicit.
[ { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "@@ -46,7 +46,6 @@ class ImportStreamer(object):\n# Define default values.\nDEFAULT_TEXT_ENCODING = 'utf-8'\nDEFAULT_TIMESTAMP_DESC = 'Time Logged'\n- DEFAULT_DATA_TYPE = 'data:entry'\ndef __init__(self):\n\"\"\"Initialize the upload streamer.\"\"\"\n@@ -55,6 +54,7 @@ class ImportStreamer(object):\nself._dict_config_loaded = False\nself._csv_delimiter = None\nself._data_lines = []\n+ self._data_type = None\nself._datetime_field = None\nself._format_string = None\nself._index = uuid.uuid4().hex\n@@ -66,7 +66,6 @@ class ImportStreamer(object):\nself._chunk = 1\n- self._data_type = self.DEFAULT_DATA_TYPE\nself._text_encoding = self.DEFAULT_TEXT_ENCODING\nself._timestamp_desc = self.DEFAULT_TIMESTAMP_DESC\nself._threshold_entry = self.DEFAULT_ENTRY_THRESHOLD\n@@ -95,6 +94,7 @@ class ImportStreamer(object):\nmy_dict['message'] = format_string.format(**my_dict)\n_ = my_dict.setdefault('timestamp_desc', self._timestamp_desc)\n+ if self._data_type:\n_ = my_dict.setdefault('data_type', self._data_type)\nif 'datetime' not in my_dict:\n@@ -144,7 +144,7 @@ class ImportStreamer(object):\nif 'timestamp_desc' not in data_frame:\ndata_frame['timestamp_desc'] = self._timestamp_desc\n- if 'data_type' not in data_frame:\n+ if self._data_type and 'data_type' not in data_frame:\ndata_frame['data_type'] = self._data_type\nif 'datetime' not in data_frame:\n" } ]
Python
Apache License 2.0
google/timesketch
Making the data_type more explicit.
263,133
09.09.2020 11:02:50
0
e3dd3b587be5051ade029ccec3ba520b0dce7dbf
Update interface.py Removed a comment that wasn't needed
[ { "change_type": "MODIFY", "old_path": "end_to_end_tests/interface.py", "new_path": "end_to_end_tests/interface.py", "diff": "@@ -61,7 +61,6 @@ class BaseEndToEndTest(object):\nfile_path = os.path.join(TEST_DATA_DIR, filename)\nprint('Importing: {0:s}'.format(file_path))\n- # Import using the importer client.\nwith importer.ImportStreamer() as streamer:\nstreamer.set_sketch(self.sketch)\nstreamer.set_timeline_name(file_path)\n" } ]
Python
Apache License 2.0
google/timesketch
Update interface.py Removed a comment that wasn't needed
263,133
09.09.2020 13:41:27
0
bd51a3b7055cafa7beead5549b861317f3909ef6
Adding more controls to search_by_label
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -1222,11 +1222,20 @@ class Sketch(resource.BaseResource):\nmeta['total_number_of_events_sent_by_client'] = len(events)\nreturn meta\n- def search_by_label(self, label_name, as_pandas=False):\n+ def search_by_label(\n+ self, label_name, return_fields=None, max_entries=None,\n+ as_pandas=False):\n\"\"\"Searches for all events containing a given label.\nArgs:\nlabel_name: A string representing the label to search for.\n+ return_fields (str): A comma separated string with a list of fields\n+ that should be included in the response. Optional and defaults\n+ to None.\n+ max_entries (int): Optional integer denoting a best effort to limit\n+ the output size to the number of events. Events are read in,\n+ 10k at a time so there may be more events in the answer back\n+ than this number denotes, this is a best effort.\nas_pandas: Optional bool that determines if the results should\nbe returned back as a dictionary or a Pandas DataFrame.\n@@ -1259,7 +1268,8 @@ class Sketch(resource.BaseResource):\n}\n}\nreturn self.explore(\n- query_dsl=json.dumps({'query': query}), as_pandas=as_pandas)\n+ query_dsl=json.dumps({'query': query}), return_fields=return_fields,\n+ max_entries=max_entries, as_pandas=as_pandas)\ndef add_event(\nself, message, date, timestamp_desc, attributes=None,\n" } ]
Python
Apache License 2.0
google/timesketch
Adding more controls to search_by_label
263,133
11.09.2020 09:27:04
0
dcf9c6ad4d7e901980fd614a4b5f7438763cd6ef
Update sigma_tagger.py Just changing the \ to make sure we don't break lines differently (consistency in codebase)
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/sigma_tagger.py", "new_path": "timesketch/lib/analyzers/sigma_tagger.py", "diff": "@@ -128,12 +128,11 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\ntagged_events_counter = self.run_sigma_rule(\nsigma_rule, tag_name)\ntags_applied[tag_name] += tagged_events_counter\n- except elasticsearch.TransportError \\\n- as es_TransportError:\n+ except elasticsearch.TransportError as e:\nlogger.error(\n'Timeout generating rule in file {0:s}: '\n'{1!s} waiting for 10 seconds'.format(\n- rule_file_path, es_TransportError))\n+ rule_file_path, e), exc_info=True)\ntime.sleep(10) # waiting 10 seconds\ntotal_tagged_events = sum(tags_applied.values())\n" } ]
Python
Apache License 2.0
google/timesketch
Update sigma_tagger.py Just changing the \ to make sure we don't break lines differently (consistency in codebase)
263,139
11.09.2020 14:15:29
-7,200
6b41465a85e3b356b8dd100aadcf49c6a309ecd0
Documentation updates Updated development docs and docker development container readme
[ { "change_type": "MODIFY", "old_path": "docker/dev/README.md", "new_path": "docker/dev/README.md", "diff": "## Docker for development\nYou can run Timesketch on Docker in development mode.\n+Make sure to follow the docker [post-install](https://docs.docker.com/engine/install/linux-postinstall/) to run without superuser. If not then make sure to execute all `docker` commands here as superuser.\nNOTE: It is not recommended to try to run on a system with less than 8 GB of RAM.\n@@ -10,12 +11,13 @@ NOTE: It is not recommended to try to run on a system with less than 8 GB of RAM\ndocker-compose up -d\n```\n+The provided container definition runs Timesketch in development mode as a volume from your cloned repo. Any changes you make will appear in Timesketch automatically.\n+\nIf you see the folowing message you can continue\n```\nTimesketch development server is ready!\n```\n-\n### Find out container ID for the timesketch container\n```\n@@ -25,7 +27,7 @@ In the output look for CONTAINER ID for the timesketch container\nTo write the ID to a variable, use:\n```\n-export CONTAINER_ID=\"$(sudo docker container list -f name=dev_timesketch -q)\"\n+export CONTAINER_ID=\"$(docker container list -f name=dev_timesketch -q)\"\n```\nand test with\n```\n@@ -34,18 +36,27 @@ echo $CONTAINER_ID\n### Start a celery container shell\n```\n-sudo docker exec -it $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n+docker exec -it $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n```\n### Start development webserver\n```\n-sudo docker exec -it $CONTAINER_ID gunicorn --reload -b 0.0.0.0:5000 --log-file - --timeout 120 timesketch.wsgi:application\n+docker exec -it $CONTAINER_ID gunicorn --reload -b 0.0.0.0:5000 --log-file - --timeout 120 timesketch.wsgi:application\n```\nYou now can access your development version at http://127.0.0.1:5000/\nLog in with user: dev password: dev\n+### Non-interactive\n+\n+Running the following as a script after `docker-compose up -d` will bring up the development environment in the background for you.\n+```\n+export CONTAINER_ID=\"$(docker container list -f name=dev_timesketch -q)\"\n+docker exec $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n+docker exec $CONTAINER_ID gunicorn --reload -b 0.0.0.0:5000 --log-file - --timeout 120 timesketch.wsgi:application\n+```\n+\n### Run tests\n```\n" }, { "change_type": "MODIFY", "old_path": "docs/Developers-Guide.md", "new_path": "docs/Developers-Guide.md", "diff": "### Developers guide\n-#### Python dependencies\n-We use pip-tools and virtualenv for development. Pip-tools must be installed\n-inside a virtualenv, installing it system-wide will cause issues.\n-If you want to add a new python dependency, please add it to `requirements.in`\n-and then run `pip-compile` to pin it's version in `requirements.txt`.\n-Use `pip-sync` instead of `pip install -r requirements.txt` when possible.\n-Use `pip-compile --upgrade` to keep dependencies up to date.\n-\n-#### Frontend dependencies\n-Add Node.js 8.x repo\n-\n- $ curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -\n- $ echo \"deb https://deb.nodesource.com/node_8.x $(lsb_release -s -c) main\" | sudo tee /etc/apt/sources.list.d/nodesource.list\n-\n-Add Yarn repo\n-\n- $ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -\n- $ echo \"deb https://dl.yarnpkg.com/debian/ stable main\" | sudo tee /etc/apt/sources.list.d/yarn.list\n-\n-Install Node.js and Yarn\n-\n- $ apt-get update && apt-get install nodejs yarn\n-\n-Cd to timesketch repository root (folder that contains `package.json` - on docker it is: `/usr/local/src/timesketch/timesketch/frontend`)\n-and install Node.js packages (this will create `node_modules/` folder in the\n-current directory and install packages from `package.json` there)\n-\n- $ yarn install\n+It is recommended to develop Timesketch using a docker container. Refer to [Docker Readme](../docker/dev/README.md) for details on how to bring up the development container.\n+\n+Note: Exclamation mark `!` denotes commands that should run in the docker container shell, dollar sign `$` denotes commands to run in your local shell.\n+\n+#### Frontend development\n+\n+First we need to get an interactive shell to the container to install the frontend modules:\n+```\n+$ docker exec -it $CONTAINER_ID bash\n+```\n+Then inside the container shell go to the Timesketch frontend directory.\n+```\n+! cd /usr/local/src/timesketch/timesketch/frontend\n+```\n+Note that this directory in the container is mounted as volume from your local repo and mirrors changes to your local repo.\n+\n+Install node dependencies\n+```\n+! npm install\n+```\n+This will create `node_modules/` folder from `package.json` in the frontend directory.\n+```\n+! yarn install\n+```\n#### Running tests and linters\n-The main entry point is `run_tests.py`. Please note that for testing and\n-linting python/frontend code you need respectively python/frontend dependencies\n-installed.\n-\n-For more information:\n-\n- $ run_tests.py --help\n-To run frontend tests in watch mode, use\n-\n- $ yarn run test:watch\n+The main entry point is `run_tests.py` in Timesketch root. Please note that for testing\n+and linting python/frontend code in your local environment you need respectively python/\n+frontend dependencies installed.\n+For more information:\n+```\n+! run_tests.py --help\n+```\n+To run frontend tests in watch mode, cd to `frontend` directory and use\n+```\n+! yarn run test --watch\n+```\nTo run TSLint in watch mode, use\n-\n- $ yarn run lint:watch\n+```\n+! yarn run lint --watch\n+```\n#### Building Timesketch frontend\n-To build frontend files and put bundles in `timesketch/static/dist/`, use\n-\n- $ yarn run build\n+To build frontend files and put bundles in `timesketch/static/dist/`, use\n+```\n+! yarn run build\n+```\nTo watch for changes in code and rebuild automatically, use\n+```\n+! yarn run build --watch\n+```\n+This is what you would normally use when making changes to the frontend.\n+Changes are not instantaneous, it takes a couple of seconds to rebuild. It's best to\n+keep this interactive shell to your container running so you can monitor the re-build.\n- $ yarn run build:watch\n+Don't forget to refresh page if your browser doesn't automatically load the changes.\n#### Packaging\n+\nBefore pushing package to PyPI, make sure you build the frontend before.\n+\n+#### Local development\n+\n+You may work on the frontend for your local environment for integration with your IDE or other reasons. This is not recommended however as it may cause clashes with your installed NodeJS.\n+\n+Add Node.js 8.x repo\n+```\n+$ curl -sS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -\n+$ echo \"deb https://deb.nodesource.com/node_8.x $(lsb_release -s -c) main\" | sudo tee /etc/apt/sources.list.d/nodesource.list\n+```\n+Add Yarn repo\n+```\n+$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -\n+$ echo \"deb https://dl.yarnpkg.com/debian/ stable main\" | sudo tee /etc/apt/sources.list.d/yarn.list\n+```\n+Install Node.js and Yarn\n+```\n+$ apt-get update && apt-get install nodejs yarn\n+```\n+After that you would run the same steps as with docker container to install frontend\n+dependencies and build/test.\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
Documentation updates (#1367) Updated development docs and docker development container readme Co-authored-by: Kristinn <kristinn@log2timeline.net> Co-authored-by: Johan Berggren <jberggren@gmail.com>
263,108
21.09.2020 20:58:46
-7,200
a846dc9655190f60b18e2f7937fd1c0c92de0c88
Add button to remove story
[ { "change_type": "MODIFY", "old_path": "timesketch/frontend/src/components/Sketch/StoryList.vue", "new_path": "timesketch/frontend/src/components/Sketch/StoryList.vue", "diff": "@@ -19,6 +19,11 @@ limitations under the License.\n<li style=\"padding:10px;border-bottom:none;\" v-for=\"story in sketch.stories\" :key=\"story.id\">\n<div>\n<router-link :to=\"{ name: 'SketchStoryContent', params: {sketchId: sketch.id, storyId: story.id}}\"><strong>{{ story.title }}</strong></router-link>\n+ <div class=\"field is-grouped is-pulled-right\" style=\"margin-top:10px;\">\n+ <p class=\"control\">\n+ <button v-on:click=\"remove(story)\" class=\"button is-small is-rounded is-danger is-outlined\">Remove</button>\n+ </p>\n+ </div>\n<br>\n<span class=\"is-size-7\">Last activity {{ story.updated_at | moment(\"YYYY-MM-DD HH:mm\") }}</span>\n</div>\n@@ -28,12 +33,24 @@ limitations under the License.\n</template>\n<script>\n+import ApiClient from '../../utils/RestApiClient'\n+\nexport default {\ndata () {\nreturn {\nstories: []\n}\n},\n+ methods: {\n+ remove(story) {\n+ ApiClient.deleteStory(this.sketch.id, story.id)\n+ .then((response) => {\n+ this.$store.dispatch('updateSketch', this.sketch.id)\n+ }).catch((e) => {\n+ console.error(e)\n+ })\n+ }\n+ },\ncomputed: {\nsketch () {\nreturn this.$store.state.sketch\n" }, { "change_type": "MODIFY", "old_path": "timesketch/frontend/src/utils/RestApiClient.js", "new_path": "timesketch/frontend/src/utils/RestApiClient.js", "diff": "@@ -166,6 +166,9 @@ export default {\n}\nreturn RestApiClient.post('/sketches/' + sketchId + /stories/ + storyId + '/', formData)\n},\n+ deleteStory (sketchId, storyId) {\n+ return RestApiClient.delete('/sketches/' + sketchId + /stories/ + storyId + '/')\n+ },\n// Saved views\ngetView (sketchId, viewId) {\nreturn RestApiClient.get('/sketches/' + sketchId + '/views/' + viewId + '/')\n" } ]
Python
Apache License 2.0
google/timesketch
Add button to remove story (#1372)
263,096
28.09.2020 22:19:21
-7,200
5928d2f4971120940cf2211be8ddab033d15186d
Update api doc * Update UploadDataViaAPI.md remove a ( that caused a link to not parse) * Update UploadDataViaAPI.md we are already in the right dir * Update UploadDataViaAPI.md be consistent with the examples, only the PCAP one had a fh instead of a file path.
[ { "change_type": "MODIFY", "old_path": "docs/UploadDataViaAPI.md", "new_path": "docs/UploadDataViaAPI.md", "diff": "# Create Timeline From Other Sources\nNot all data comes in a good [CSV or JSONL\n-format](docs/CreateTimelineFromJSONorCSV.md) that can be imported\n+format](CreateTimelineFromJSONorCSV.md) that can be imported\ndirectly into Timesketch. Your data may lie in a SQL database, Excel sheet, or\neven in CSV/JSON but it does not have the correct fields in it. In those cases\nit might be beneficial to have a separate importer in Timesketch that can deal\n@@ -94,7 +94,7 @@ Timestamp What URL Results\nHere we have a data frame that we may want to add to our Timesketch instance.\nWhat is missing here are few of the necessary columns, see\n-[documentation]((docs/CreateTimelineFromJSONorCSV.md). We don't really need to\n+[documentation](CreateTimelineFromJSONorCSV.md). We don't really need to\nadd them here, we can do that all in our upload stream. Let's start by\nconnecting to a Timesketch instance.\n@@ -134,7 +134,7 @@ from the network traffic to Timesketch.\nfrom scapy import all as scapy_all\n...\n-packets = scapy_all.rdpcap(fh)\n+packets = scapy_all.rdpcap(~/Downloads/SomeRandomDocument.pcap)\nwith importer.ImportStreamer() as streamer:\nstreamer.set_sketch(my_sketch)\n" } ]
Python
Apache License 2.0
google/timesketch
Update api doc (#1378) * Update UploadDataViaAPI.md remove a ( that caused a link to not parse) * Update UploadDataViaAPI.md we are already in the right dir * Update UploadDataViaAPI.md be consistent with the examples, only the PCAP one had a fh instead of a file path.
263,133
01.10.2020 13:27:13
0
117ac5bf89aa5cc6b91b6dcab3561214854cb7f8
Adding the ability to add labels to sketches.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -58,7 +58,6 @@ class Sketch(resource.BaseResource):\nself.id = sketch_id\nself.api = api\nself._archived = None\n- self._labels = []\nself._sketch_name = sketch_name\nself._resource_uri = 'sketches/{0:d}'.format(self.id)\nsuper(Sketch, self).__init__(api=api, resource_uri=self._resource_uri)\n@@ -79,22 +78,17 @@ class Sketch(resource.BaseResource):\n@property\ndef labels(self):\n\"\"\"Property that returns the sketch labels.\"\"\"\n- if self._labels:\n- return self._labels\n-\n- data = self.lazyload_data()\n+ data = self.lazyload_data(refresh_cache=True)\nobjects = data.get('objects', [])\nif not objects:\n- return self._labels\n+ return []\nsketch_data = objects[0]\nlabel_string = sketch_data.get('label_string', '')\nif label_string:\n- self._labels = json.loads(label_string)\n- else:\n- self._labels = []\n+ return json.loads(label_string)\n- return self._labels\n+ return []\n@property\ndef name(self):\n@@ -180,6 +174,67 @@ class Sketch(resource.BaseResource):\nreturn data_frame\n+ def add_sketch_label(self, label):\n+ \"\"\"Add a label to the sketch.\n+\n+ Args:\n+ label (str): A string with the label to add to the sketch.\n+\n+ Returns:\n+ bool: A boolean to indicate whether the label was successfully\n+ added to the sketch.\n+ \"\"\"\n+ if label in self.labels:\n+ logger.error(\n+ 'Label [{0:s}] already applied to sketch.'.format(label))\n+ return False\n+\n+ resource_url = '{0:s}/sketches/{1:d}/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'labels': [label],\n+ 'label_action': 'add',\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ logger.error('Unable to add the label to the sketch.')\n+\n+ return status\n+\n+ def remove_sketch_label(self, label):\n+ \"\"\"Remove a label from the sketch.\n+\n+ Args:\n+ label (str): A string with the label to remove from the sketch.\n+\n+ Returns:\n+ bool: A boolean to indicate whether the label was successfully\n+ removed from the sketch.\n+ \"\"\"\n+ if label not in self.labels:\n+ logger.error(\n+ 'Unable to remove label [{0:s}], not a label '\n+ 'attached to this sketch.'.format(label))\n+ return False\n+\n+ resource_url = '{0:s}/sketches/{1:d}/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'labels': [label],\n+ 'label_action': 'remove',\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ logger.error('Unable to remove the label from the sketch.')\n+\n+ return status\n+\ndef create_view(\nself, name, query_string='', query_dsl='', query_filter=None):\n\"\"\"Create a view object.\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/version.py", "new_path": "api_client/python/timesketch_api_client/version.py", "diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20200910'\n+__version__ = '20201001'\ndef get_version():\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources/sketch.py", "new_path": "timesketch/api/v1/resources/sketch.py", "diff": "@@ -115,6 +115,26 @@ class SketchListResource(resources.ResourceMixin, Resource):\nclass SketchResource(resources.ResourceMixin, Resource):\n\"\"\"Resource to get a sketch.\"\"\"\n+ def _add_label(self, sketch, label):\n+ \"\"\"Add a label to the sketch.\"\"\"\n+ if sketch.has_label(label):\n+ logger.warning(\n+ 'Unable to apply the label [{0:s}] to sketch {1:d}, '\n+ 'already exists.'.format(label, sketch.id))\n+ return False\n+ sketch.add_label(label, user=current_user)\n+ return True\n+\n+ def _remove_label(self, sketch, label):\n+ \"\"\"Removes a label to the sketch.\"\"\"\n+ if not sketch.has_label(label):\n+ logger.warning(\n+ 'Unable to remove the label [{0:s}] to sketch {1:d}, '\n+ 'label does not exist.'.format(label, sketch.id))\n+ return False\n+ sketch.remove_label(label)\n+ return True\n+\ndef _get_sketch_for_admin(self, sketch):\n\"\"\"Returns a limited sketch view for adminstrators.\n@@ -352,24 +372,50 @@ class SketchResource(resources.ResourceMixin, Resource):\nReturns:\nA sketch in JSON (instance of flask.wrappers.Response)\n\"\"\"\n- form = forms.NameDescriptionForm.build(request)\nsketch = Sketch.query.get_with_acl(sketch_id)\nif not sketch:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n- if not form.validate_on_submit():\n- abort(\n- HTTP_STATUS_CODE_BAD_REQUEST, (\n- 'Unable to rename sketch, '\n- 'unable to validate form data'))\n-\nif not sketch.has_permission(current_user, 'write'):\nabort(HTTP_STATUS_CODE_FORBIDDEN,\n'User does not have write access controls on sketch.')\n- sketch.name = form.name.data\n- sketch.description = form.description.data\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ update_object = False\n+ name = form.get('name', '')\n+ if name:\n+ sketch.name = name\n+ update_object = True\n+\n+ description = form.get('description', '')\n+ if description:\n+ sketch.description = description\n+ update_object = True\n+\n+ labels = form.get('labels', [])\n+ label_action = form.get('label_action', 'add')\n+ if label_action not in ('add', 'remove'):\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Label actions needs to be either \"add\" or \"remove\", '\n+ 'not [{0:s}]'.format(label_action))\n+\n+ if labels and isinstance(labels, (tuple, list)):\n+ for label in labels:\n+ if label_action == 'add':\n+ changed = self._add_label(sketch=sketch, label=label)\n+ elif label_action == 'remove':\n+ changed = self._remove_label(sketch=sketch, label=label)\n+\n+ if changed:\n+ update_object = True\n+\n+ if update_object:\ndb_session.add(sketch)\ndb_session.commit()\n+\nreturn self.to_json(sketch, status_code=HTTP_STATUS_CODE_CREATED)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to add labels to sketches.
263,133
01.10.2020 13:38:43
0
a32a9d3f18b2c3ead5998844f55184135fc8e265
Adding the ability to change name/description of a sketch.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -102,6 +102,26 @@ class Sketch(resource.BaseResource):\nself._sketch_name = sketch['objects'][0]['name']\nreturn self._sketch_name\n+ @name.setter\n+ def name(self, name_value):\n+ \"\"\"Change the name of the sketch to a new value.\"\"\"\n+ if not isinstance(name_value, str):\n+ logger.error('Unable to change the name to a non string value')\n+ return\n+\n+ resource_url = '{0:s}/sketches/{1:d}/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'name': name_value,\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+ _ = error.check_return_status(response, logger)\n+\n+ # Force the new name to be re-loaded.\n+ self._sketch_name = ''\n+ _ = self.lazyload_data(refresh_cache=True)\n+\n@property\ndef description(self):\n\"\"\"Property that returns sketch description.\n@@ -112,6 +132,25 @@ class Sketch(resource.BaseResource):\nsketch = self.lazyload_data()\nreturn sketch['objects'][0]['description']\n+ @description.setter\n+ def description(self, description_value):\n+ \"\"\"Change the sketch description to a new value.\"\"\"\n+ if not isinstance(description_value, str):\n+ logger.error('Unable to change the name to a non string value')\n+ return\n+\n+ resource_url = '{0:s}/sketches/{1:d}/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'description': description_value,\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+ _ = error.check_return_status(response, logger)\n+\n+ # Force the new description to be re-loaded.\n+ _ = self.lazyload_data(refresh_cache=True)\n+\n@property\ndef status(self):\n\"\"\"Property that returns sketch status.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to change name/description of a sketch.