├── .dockerignore ├── .github ├── ISSUE_TEMPLATE │ └── bug-report.md └── workflows │ ├── codeql.yml │ └── documentation.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── config_template.yaml ├── docker-compose.yaml ├── docs ├── architecture.md ├── developer_guide.md ├── index.md ├── quickstart.md ├── setup.md ├── style_guide.md ├── troubleshooting.md ├── updating.md └── usage.md ├── mkdocs.yml ├── pdm.lock ├── pyproject.toml ├── requirements.txt ├── src └── terminal_sync │ ├── __init__.py │ ├── __main__.py │ ├── api.py │ ├── config.py │ ├── export_csv.py │ ├── ghostwriter.py │ └── log_entry.py ├── terminal_sync.psm1 ├── terminal_sync.sh ├── terminal_sync_zsh.sh └── tests └── test_log_entry.py /.dockerignore: -------------------------------------------------------------------------------- 1 | # Exclude anything beginning with `.` 2 | .* 3 | 4 | # Explicitly exclude git and editor files (just in case) 5 | **/.git 6 | **/.github 7 | **/.gitignore 8 | **/.gitattributes 9 | **/.vscode 10 | 11 | # Exclude Docker and Docker Compose files 12 | **/Dockerfile 13 | docker-compose.yaml 14 | 15 | # Exclude project documentation 16 | docs 17 | # CONTRIBUTORS.txt 18 | LICENSE 19 | mkdocs.yml 20 | 21 | # Exclude local cached files 22 | **/__pycache__ 23 | build 24 | 25 | # Exclude other files not needed in a container 26 | **/config_template.yaml 27 | **/log_archive 28 | config.yaml 29 | terminal_sync.* 30 | tests 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: breakid 7 | --- 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | ## Expected Behavior 16 | 17 | 18 | ## Current Behavior 19 | 20 | 21 | ## Possible Solution 22 | 23 | 24 | ## Steps to Reproduce 25 | 26 | 27 | 1. 28 | 2. 29 | 3. 30 | 4. 31 | 32 | ## Screenshots 33 | 34 | 35 | ## Environment 36 | 37 | - terminal_sync version: 38 | - OS (client host): 39 | - OS (server host): 40 | - Are you running the client and server on the same host?: 41 | - Python version: 42 | - Docker version: 43 | - Ghostwriter version: 44 | 45 | ## Additional Context 46 | 47 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "main" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "main" ] 20 | schedule: 21 | - cron: '40 23 * * 1' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'python' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Use only 'java' to analyze code written in Java, Kotlin or both 38 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both 39 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 40 | 41 | steps: 42 | - name: Checkout repository 43 | uses: actions/checkout@v3 44 | 45 | # Initializes the CodeQL tools for scanning. 46 | - name: Initialize CodeQL 47 | uses: github/codeql-action/init@v2 48 | with: 49 | languages: ${{ matrix.language }} 50 | # If you wish to specify custom queries, you can do so here or in a config file. 51 | # By default, queries listed here will override any specified in a config file. 52 | # Prefix the list here with "+" to use these queries and those in the config file. 53 | 54 | # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 55 | # queries: security-extended,security-and-quality 56 | 57 | - name: Perform CodeQL Analysis 58 | uses: github/codeql-action/analyze@v2 59 | with: 60 | category: "/language:${{matrix.language}}" 61 | -------------------------------------------------------------------------------- /.github/workflows/documentation.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | name: Docs 3 | 4 | # Controls when the workflow will run 5 | on: 6 | # Triggers the workflow on push or pull request events but only for the main branch 7 | push: 8 | branches: [main] 9 | 10 | # Allows you to run this workflow manually from the Actions tab 11 | workflow_dispatch: 12 | 13 | permissions: 14 | contents: write 15 | 16 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 17 | jobs: 18 | # This workflow contains a single job called "build" 19 | build: 20 | # The type of runner that the job will run on 21 | runs-on: ubuntu-latest 22 | 23 | # Steps represent a sequence of tasks that will be executed as part of the job 24 | steps: 25 | # Checks out your repository under $GITHUB_WORKSPACE, so your job can access it 26 | - uses: actions/checkout@v3 27 | - uses: actions/setup-python@v4 28 | - run: pip install --upgrade pip && pip install mkdocs mkdocs-gen-files 29 | # See [Deploying your docs](https://www.mkdocs.org/user-guide/deploying-your-docs/) 30 | - name: Publish docs 31 | run: mkdocs gh-deploy #--config-file docs/mkdocs.yml 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pdm 89 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 90 | #pdm.lock 91 | # pdm stores project-wide configurations in .pdm.toml or .pdm-python, but it is recommended to not include it 92 | # in version control. 93 | # https://pdm.fming.dev/#use-with-ide 94 | .pdm.toml 95 | .pdm-python 96 | 97 | # pipenv 98 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 99 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 100 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 101 | # install all needed dependencies. 102 | #Pipfile.lock 103 | 104 | # poetry 105 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 106 | # This is especially recommended for binary packages to ensure reproducibility, and is more 107 | # commonly ignored for libraries. 108 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 109 | #poetry.lock 110 | 111 | # pyenv 112 | # For a library or package, you might want to ignore these files since the code is 113 | # intended to run in multiple environments; otherwise, check them in: 114 | # .python-version 115 | 116 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 117 | __pypackages__/ 118 | 119 | # Celery stuff 120 | celerybeat-schedule 121 | celerybeat.pid 122 | 123 | # SageMath parsed files 124 | *.sage.py 125 | 126 | # Environments 127 | .env 128 | .venv 129 | env/ 130 | venv/ 131 | ENV/ 132 | env.bak/ 133 | venv.bak/ 134 | 135 | # Spyder project settings 136 | .spyderproject 137 | .spyproject 138 | 139 | # Rope project settings 140 | .ropeproject 141 | 142 | # mkdocs documentation 143 | /site 144 | 145 | # mypy 146 | .mypy_cache/ 147 | .dmypy.json 148 | dmypy.json 149 | 150 | # Pyre type checker 151 | .pyre/ 152 | 153 | # pytype static type analyzer 154 | .pytype/ 155 | 156 | # Cython debug symbols 157 | cython_debug/ 158 | 159 | # PyCharm 160 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 161 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 162 | # and can be added to the global gitignore or merged into this file. For a more nuclear 163 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 164 | #.idea/ 165 | 166 | # Local VS Code configs 167 | .vscode 168 | *.code-workspace 169 | 170 | 171 | # Custom 172 | log_archive/ 173 | config.yaml 174 | 175 | # Bash dependency downloaded to project repo directory (by default) 176 | bash-preexec.sh -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # USAGE NOTES 2 | # 3 | # To setup, run: 4 | # 5 | # pre-commit install 6 | # 7 | # and then you can do your normal git add + git commit or run: 8 | # 9 | # pre-commit run --all-files 10 | # 11 | # If you edit this file, you need to re-run `pre-commit install` 12 | # 13 | # Source: https://github.com/pre-commit/pre-commit-hooks 14 | # Source: https://github.com/apwheele/retenmod/blob/main/.pre-commit-config.yaml 15 | 16 | exclude: ".git|.tox|docs" 17 | #fail_fast: true 18 | default_language_version: 19 | python: python3 20 | 21 | ci: 22 | autofix_commit_msg: | 23 | fix: Auto fix by pre-commit [pre-commit.ci] 24 | 25 | For more information, see https://pre-commit.ci 26 | autoupdate_commit_msg: "fix: Pre-commit autoupdate [pre-commit.ci]" 27 | 28 | repos: 29 | - repo: https://github.com/pdm-project/pdm 30 | rev: 2.5.3 31 | hooks: 32 | # Ensure pdm.lock is up-to-date 33 | - id: pdm-lock-check 34 | 35 | # Export production dependencies to requirements.txt 36 | - id: pdm-export 37 | args: ["--prod", "-o", "requirements.txt", "--without-hashes"] 38 | files: ^pdm.lock$ 39 | 40 | - repo: https://github.com/pre-commit/pre-commit-hooks 41 | rev: v4.4.0 42 | hooks: 43 | # Prevent giant files from being committed 44 | - id: check-added-large-files 45 | 46 | # Check whether files parse as valid python 47 | - id: check-ast 48 | 49 | # Check for files with names that would conflict on a case-insensitive filesystem 50 | - id: check-case-conflict 51 | 52 | # Checks for a common error of placing code before the docstring 53 | - id: check-docstring-first 54 | 55 | # Checks that non-binary executables have a proper shebang. 56 | - id: check-executables-have-shebangs 57 | 58 | # Attempts to load all json files to verify syntax 59 | - id: check-json 60 | 61 | # Check for files that contain merge conflict strings 62 | - id: check-merge-conflict 63 | 64 | # Checks for symlinks which do not point to anything 65 | - id: check-symlinks 66 | 67 | # Attempts to load all TOML files to verify syntax 68 | - id: check-toml 69 | 70 | # Ensures that links to version control system (VCS) websites are permalinks 71 | - id: check-vcs-permalinks 72 | 73 | # Attempts to load all xml files to verify syntax 74 | - id: check-xml 75 | 76 | # Attempts to load all yaml files to verify syntax 77 | - id: check-yaml 78 | 79 | # Check for debugger imports and py37+ breakpoint() calls in python source 80 | - id: debug-statements 81 | 82 | # Detects symlinks which are changed to regular files with a content of a path which that symlink was pointing to 83 | - id: destroyed-symlinks 84 | 85 | # Makes sure files end in a newline and only a newline 86 | - id: end-of-file-fixer 87 | 88 | # Verifies that test files are named correctly 89 | - id: name-tests-test 90 | args: [--pytest-test-first] 91 | 92 | # Ensure JSON is pretty printed 93 | - id: pretty-format-json 94 | args: [--autofix, --no-ensure-ascii] 95 | 96 | # Trims trailing whitespace 97 | - id: trailing-whitespace 98 | 99 | # Automatically upgrade syntax for newer versions of the language 100 | - repo: https://github.com/asottile/pyupgrade 101 | rev: v3.3.1 102 | hooks: 103 | - id: pyupgrade 104 | args: [--py38-plus] 105 | 106 | # Enforce that python3.6+ type annotations are used instead of type comments 107 | - repo: https://github.com/pre-commit/pygrep-hooks 108 | rev: v1.10.0 109 | hooks: 110 | - id: python-use-type-annotations 111 | 112 | # Apply mypy static type checking 113 | - repo: https://github.com/pre-commit/mirrors-mypy 114 | rev: v1.2.0 115 | hooks: 116 | - id: mypy 117 | additional_dependencies: [types-PyYAML] 118 | 119 | # Sort imports and add section headers 120 | - repo: https://github.com/pycqa/isort 121 | rev: 5.12.0 122 | hooks: 123 | - id: isort 124 | name: isort (python) 125 | # See pyproject.toml for config options 126 | 127 | # Format code using Black 128 | - repo: https://github.com/psf/black 129 | rev: 23.3.0 130 | hooks: 131 | - id: black 132 | # See pyproject.toml for config options 133 | 134 | # flake8 is a python tool that glues together pycodestyle, pyflakes, mccabe, and third-party plugins to check the 135 | # style and quality of some python code 136 | - repo: https://github.com/PyCQA/flake8 137 | rev: 6.0.0 138 | hooks: 139 | - id: flake8 140 | args: [-v] 141 | # Use a plugin to read the config from pyproject.toml 142 | # Alternatively, could use `pyproject-flake8` 143 | # See https://github.com/csachs/pyproject-flake8/issues/3#issuecomment-863976991 144 | additional_dependencies: [Flake8-pyproject] 145 | 146 | # Check for missing docstrings 147 | - repo: https://github.com/econchick/interrogate 148 | rev: 1.5.0 149 | hooks: 150 | - id: interrogate 151 | # See pyproject.toml for config options 152 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [v0.3.0] - 2023-05-02 9 | 10 | ### Added 11 | 12 | - Developer documentation 13 | 14 | ### Fixed 15 | 16 | - Fixed a bug where multiple JSON objects were created for the same command if an exception occurred during creation 17 | - Added missing `source_host` and `operator` fields to messages sent by the Bash client 18 | 19 | ### Changed 20 | 21 | - Split README content into separate pages and added more details / explanations 22 | 23 | ## [v0.2.0] - 2023-04-26 24 | 25 | ### Added 26 | 27 | - Added a new feature to save failed (or optionally all) logs locally (as JSON files) 28 | - Created a script / library to export the JSON files to a GhostWriter CSV 29 | - Configured the server to automatically export a CSV file on shutdown (though stopping a Docker container doesn't seem to trigger it) 30 | 31 | ### Fixed 32 | 33 | - Fixed several syntax errors in the Bash install / hook script that prevented successful installation 34 | 35 | ### Changed 36 | 37 | - Updated Dockerfile to export requirements.txt (to ensure platform compatibility) and install using pip rather than PDM (to reduce runtime complexity) 38 | - Increased minimum Python version to 3.10 due to use of PEP-604 style type hinting syntax 39 | - Reduced default timeout values as the previous ones were painfully long if something failed and would negatively impact user experience 40 | 41 | ## [v0.1.0] - 2023-04-21 42 | 43 | Initial release 44 | 45 | ### Added 46 | 47 | - FastAPI server with command create and update endpoints 48 | - Custom config class 49 | - `config.yaml` template 50 | - GhostWriter client 51 | - Dockerfile and Docker Compose config that build a terminal_sync server image 52 | - Bash script that installs dependencies and contains pre-exec and post-exec hooks 53 | - PowerShell module containing pre-exec and post-exec hooks 54 | - `README.md` documenting how to install, update, use, and troubleshoot terminal_sync 55 | - Project management files (`CHANGELOG.md`, `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`) 56 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | TBD. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | . 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | . Translations are available at 128 | . 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | Thank you for taking the time to learn how to contribute! 4 | 5 | Please start by reviewing our [Code of Conduct](/CODE_OF_CONDUCT.md) to ensure our community remains respectful and approachable. By participating, you will be expected to uphold this code. 6 | 7 | ## Questions 8 | 9 | If you have a question, please check the [documentation](https://breakid.github.io/terminal_sync/) and search previous [Q&As](https://github.com/breakid/terminal_sync/discussions/categories/q-a) first. If you cannot find an answer, please post your question [here](https://github.com/breakid/terminal_sync/discussions/new?category=q-a) (i.e., create a new discussion under the **Q&A** category of the **Discussions** tab). 10 | 11 | The following is a set of guidelines for contributing to Ghostwriter and its packages, which are hosted in the GhostManager Organization on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 12 | 13 | ## Basics of Contributing to the Project 14 | 15 | The project team welcomes feedback, new ideas, and external contributions. The following sections provide details on specific types of contributions. 16 | 17 | ### Reporting an Issue/Bug 18 | 19 | Before submitting an issue, please do the following: 20 | 21 | 1. Make sure you are using the latest release (check the version number in the `pyproject.toml` file) 22 | 2. Check open and closed issues for any related discussions 23 | 24 | When submitting a new issue use the provided template. Please fill out the questions to ensure we have the basic information we need to review and reproduce the issue. 25 | 26 | ### Suggesting a Change or New Feature 27 | 28 | Start by reviewing the [terminal_sync Roadmap](https://github.com/users/breakid/projects/1) under the **Projects** tab and the [Ideas](https://github.com/breakid/terminal_sync/discussions/categories/ideas) section under the **Discussions** tab. If your idea is already being discussed, feel free to comment on it to add your support. 29 | 30 | Please submit new ideas [here](https://github.com/breakid/terminal_sync/discussions/new?category=ideas) (i.e., the **Ideas** section of the **Discussion** tab). Provide clear and concise answers to the following questions. 31 | 32 | - What problem are you having or trying to solve? 33 | - How do you measure success? 34 | - What is your desired outcome? 35 | - What would a successful solution look like? 36 | - What alternatives have you considered or tried? 37 | - What additional context is necessary to understand your request? 38 | 39 | ### Submitting a Pull Request 40 | 41 | The process described here has several goals: 42 | 43 | - Maintain code quality 44 | - Fix problems that are important to users 45 | - Engage the community in working toward the best possible solution 46 | - Enable a sustainable system for maintainers to review contributions 47 | 48 | Please follow these steps to have your contribution considered by the maintainers: 49 | 50 | 1. Review the [Developer Guide](https://breakid.github.io/terminal_sync/developer_guide/) and follow the [Style Guide](https://breakid.github.io/terminal_sync/style_guide/) 51 | 2. Follow all instructions in the pull request template (coming soon) 52 | 3. After you submit your pull request, verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing
What if the status checks are failing?If a status check is failing, and you believe that the failure is unrelated to your change, please leave a comment on the pull request explaining why you believe the failure is unrelated. A maintainer will re-run the status check for you. If we conclude that the failure was a false positive, then we will open an issue to track that problem with our status check suite.
53 | 54 | These prerequisites must be satisfied prior to your pull request being reviewed; however, the reviewer(s) may ask you to complete additional design work, tests, or other changes before accepting your pull request. 55 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Install PDM and use it to export requirements.txt to ensure platform compatibility 2 | FROM python:3.11-slim as requirements-stage 3 | 4 | WORKDIR /tmp 5 | 6 | RUN pip install pdm 7 | 8 | # Copy the pyproject.toml and pdm.lock files to the /tmp directory 9 | # Because it uses ./pdm.lock* (ending with a *), it won't crash if that file is not available 10 | COPY ./pyproject.toml ./pdm.lock* /tmp/ 11 | 12 | # Generate requirements.txt 13 | RUN pdm export --prod --without-hashes -o requirements.txt 14 | 15 | # Build the final image 16 | FROM python:3.11-slim 17 | 18 | # ENV LANG=C.UTF-8 # Defined in the base image 19 | ENV LC_ALL=C.UTF-8 20 | ENV LC_TIME=C.UTF-8 21 | ENV LISTEN_PORT=8000 22 | # Enable Python optimizations 23 | ENV PYTHONOPTIMIZE=1 24 | 25 | WORKDIR /app 26 | 27 | # Copy the requirements.txt file from the previous stage 28 | COPY --from=requirements-stage /tmp/requirements.txt /app/requirements.txt 29 | 30 | # Upgrade pip and install / upgrade required packages 31 | RUN pip install --no-cache-dir --upgrade pip && pip install --no-cache-dir --upgrade -r requirements.txt 32 | 33 | # Copy the application code into the container 34 | COPY ./src/terminal_sync ./terminal_sync 35 | 36 | EXPOSE $LISTEN_PORT/tcp 37 | 38 | # FastAPI has a built-in /docs endpoint that we can use to check whether the server is running properly 39 | HEALTHCHECK CMD curl --fail http://localhost:$LISTEN_PORT/docs || exit 1 40 | 41 | # Run terminal_sync as a module 42 | # IMPORTANT: This must listen on 0.0.0.0 or else the application will not be accessible outside of the container 43 | CMD python3 -m terminal_sync --host 0.0.0.0 --port $LISTEN_PORT 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # terminal_sync 2 | 3 | **No Longer Maintained**: I rewrote terminal_sync as a pure CLI application, without the overhead, complexity, or security risks of FastAPI. This new version also supported plugin-based command parsing; however, testing was incomplete when I lost motivation to work on this project. After intending to finish these changes for almost a year, I've decided to officially shelve this project. For anyone who is interested, I highly recommend checking out and finishing the new version, which is available on the `cli_client` branch. I'll leave the project active, for now, in case anyone wants to submit a pull request for the finalized CLI client. 4 | 5 | terminal_sync is a standalone tool for logging Bash and PowerShell commands to [GhostWriter](https://github.com/GhostManager/Ghostwriter) automatically. The provided Bash script and PowerShell module register pre-exec and post-exec hooks that capture executed commands and function as clients, sending command information to the terminal_sync server for additional processing and enrichment. Any commands that meet the logging criteria (e.g., contain a specific keyword) are sent to GhostWriter. 6 | 7 | For more information, including [how to get started](https://breakid.github.io/terminal_sync/setup), please refer to our [documentation](https://breakid.github.io/terminal_sync/) 8 | 9 | --- 10 | 11 | ## Features 12 | 13 | - **Automatic Shell Logging** 14 | - Logs Bash and PowerShell commands directly to GhostWriter based on a configurable keyword list 15 | 16 | - **Export Log Entries to CSV** 17 | - Saves failed (or optionally all) command log entries to JSON files that can be [converted to CSV](usage.md#export-logs-to-ghostwriter-csv) and imported into GhostWriter 18 | - Supports off-line logging 19 | 20 | - **Command Timestamps** 21 | - Displays execution and completion timestamps for each command 22 | - Useful reference for commands not configured to auto-log 23 | 24 | - **In-line Descriptions** 25 | - Supports [adding a description](usage.md#add-a-description) to the end of a command 26 | - Allows users to [force an individual command to be logged](usage.md#log-ad-hoc-commands) 27 | - Maintains flow by keeping users at the command-line 28 | 29 | - **Simple Configuration** 30 | - Easy [setup and configuration using YAML config file and/or environment variables](setup.md#2-configure-the-server) 31 | 32 | - **Management Commands** 33 | - Ability to [enable/disable terminal_sync](usage.md#enable--disable-terminal_sync) or [change the verbosity](usage.md#adjust-console-output-at-runtime) for an individual session 34 | 35 | --- 36 | 37 | ## References 38 | 39 | - [Ghostwriter](https://github.com/GhostManager/Ghostwriter) - Engagement Management and Reporting Platform 40 | - [Ghostwriter Documentation - Operation Logs](https://www.ghostwriter.wiki/features/operation-logs) - Guidance on operation logging setup and usage with Ghostwriter 41 | 42 | --- 43 | 44 | ## Credits 45 | 46 | Many thanks to: 47 | 48 | - Everyone who contributed to [GhostWriter](https://github.com/GhostManager/Ghostwriter) and specifically [chrismaddalena](https://github.com/chrismaddalena), [its-a-feature](https://github.com/its-a-feature), and [hotnops](https://github.com/hotnops) for their work on [mythic_sync](https://github.com/GhostManager/mythic_sync) (GraphQL) and [mythic-sync](https://github.com/hotnops/mythic-sync) (REST), from which terminal_sync "borrowed" liberally 49 | - [rcaloras](https://github.com/rcaloras) and everyone who contributed to [bash-preexec](https://github.com/rcaloras/bash-preexec) 50 | - Finding this tool inspired me to build the first prototype of what later became terminal_sync 51 | -------------------------------------------------------------------------------- /config_template.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # The URL for your GhostWriter instance (e.g., "https://ghostwriter.example.com") 3 | gw_url: "" 4 | 5 | # The ID number of the GhostWriter Oplog where entries will be recorded. This can be found in the Oplog URL 6 | # Example: "/oplog//entries" 7 | gw_oplog_id: 0 8 | 9 | # One of the following GhostWriter API keys MUST be specified; if both are specified, terminal_sync 10 | # will default to using the GraphQL API 11 | 12 | # A GhostWriter GraphQL API key. To generate: 13 | # 1. Login to GhostWriter 14 | # 2. Click on your user profile icon in the upper-right corner 15 | # 3. Scroll down to the **API Tokens** section and click **Create** 16 | # 4. Provide a name and expiration date, then click **Submit** 17 | gw_api_key_graphql: 18 | 19 | # A GhostWriter REST API key. This key is generated when, and only when, a new Oplog is created 20 | gw_api_key_rest: 21 | 22 | # Anything appearing after this token in a shell command will be logged to the entry's Description field 23 | # It must begin with a "#" so that Bash and PowerShell will interpret it and everything that follows as a comment 24 | # Note: Including this token will force any command where it is provided to be logged 25 | #gw_description_token: "#desc" 26 | 27 | # Name/identifier of the user creating the log entries 28 | #operator: 29 | 30 | # The directory where JSON log files are written 31 | #termsync_json_log_dir: "log_archive" 32 | 33 | # List of keywords that will trigger logging a command to GhostWriter 34 | # The `gw_description_token` is automatically added to this list 35 | termsync_keywords: 36 | - aws 37 | - kubectl 38 | - proxychains 39 | # The host address where the server will bind 40 | #termsync_listen_host: "127.0.0.1" 41 | 42 | # The host port where the server will bind 43 | #termsync_listen_port: 8000 44 | 45 | # Whether to save all logs using the JSON file (will incur a performance penalty) 46 | #termsync_save_all_local: no 47 | 48 | # The number of seconds the server will wait for a response from GhostWriter 49 | #termsync_timeout_seconds: 3 50 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | version: "3" 3 | 4 | services: 5 | server: 6 | build: 7 | context: . 8 | dockerfile: ./Dockerfile 9 | image: "terminal_sync:latest" 10 | restart: unless-stopped 11 | ports: 12 | - "8000:8000" 13 | # environment: 14 | # - GW_URL= 15 | # - GW_OPLOG_ID= 16 | # - GW_API_KEY_GRAPHQL= 17 | # - GW_API_KEY_REST= 18 | # - OPERATOR= 19 | volumes: 20 | - ./config.yaml:/app/config.yaml 21 | - ./log_archive:/app/log_archive 22 | - ./terminal_sync.log:/app/terminal_sync.log 23 | -------------------------------------------------------------------------------- /docs/architecture.md: -------------------------------------------------------------------------------- 1 | # terminal_sync Architecture 2 | 3 | This page provides additional details about how terminal_sync works and is intended for those who are: 4 | 5 | 1. Interested in contributing to the project 6 | 2. Passionately curious 7 | 8 | --- 9 | 10 | ## Design Evolution 11 | 12 | terminal_sync began life as a prototype intended specifically for capturing command-line tools, such as Impacket scripts, run with `proxychains`. The original version was a Python script called directly from the Bash pre-exec hook. Unfortunately, this had several limitations. 13 | 14 | 1. It only supported commands run via proxychains 15 | 2. It only supported Bash 16 | 3. The lack of a post-exec hook meant it couldn't capture when a command completed or its success/failure status 17 | 4. There was no way to provide a description 18 | 19 | The second iteration set out to address these issues. The first challenge was how to save state so that the completion time and output of a command could be matched to the original execution, thus allowing the initial log entry to be updated rather than creating a near duplicate entry. There was also a concern that, as the application configuration became more complex, the overhead of loading the config each time the script was run (i.e., before and after each execution) would negatively impact performance and the overall user experience. 20 | 21 | This second iteration used a client-server model where the server, which contained the majority of the processing logic, would load the configuration once and stay running. The client would remain lightweight and naive, containing only enough logic to capture raw data and send it to the server. Additionally, the clients would be written using native capabilities (i.e., Bash and PowerShell) to minimize dependencies, both for security and ease of installation. 22 | 23 | --- 24 | 25 | ## How terminal_sync Works 26 | 27 | The current version of terminal_sync uses a client-server model. 28 | 29 | ### Server 30 | 31 | The terminal_sync server is a Python package consisting of four main components: 32 | 33 | 1. Config class 34 | - Defined in `config.py` 35 | 2. GhostWriterClient class 36 | - Defined in `ghostwriter.py` 37 | 3. FastAPI server 38 | - Defined in `api.py` 39 | 4. Entry class 40 | - Defined in `log_entry.py` 41 | 42 | The server must be installed or run as a module since it uses absolute imports to reference internal modules. This was done to prevent `isort` from grouping the internal modules into the third-party libraries import section. 43 | 44 | #### Config 45 | 46 | The `Config` class defines default settings, loads the YAML config file (if it exists), and checks for any environment variables that match defined settings. If the optional `python-dotenv` package is installed, environment variables will be loaded from a `.env` file before loading the YAML config. This is done because the path to the config file can be specified using the `TERMSYNC_CONFIG` variable. If `TERMSYNC_CONFIG` was included in the `.env` file but the environment variables were loaded later, the wrong config file would be loaded, which would likely confuse users. All other environment variables are evaluated after, and therefore override values from, the YAML config file. Finally, some additional validation is performed and the config object is returned. 47 | 48 | #### GhostWriter Client 49 | 50 | The GhostWriter client is largely a consolidation of the REST-based [mythic-sync](https://github.com/hotnops/mythic-sync) and GraphQL-based [mythic_sync](https://github.com/GhostManager/mythic_sync) projects with some logic to determine which flow to use based on which API key was provided. Additionally, the exception handling was moved to the API server to allow it to send error messages back to the client. 51 | 52 | #### API Server 53 | 54 | The API server uses FastAPI to create two REST endpoints, `POST /commands/` and `PUT /commands/`, intended to create and update command log entries, respectively. In practice, the update endpoint will also create an entry if a matching one is not found in the internal buffer; this is to increase the likelihood of a command being logged successfully, even if the initial creation attempt failed. Since both endpoints contain nearly identical logic, the majority of the work is done in the shared `log_command()` function. This function checks whether the input command contains any keywords that would trigger logging. If so, the description is split from the command (if applicable), an `Entry` object is either created or retrieved from the internal buffer and updated, then the `Entry` object is sent to the GhostWriter client, which sends it to GhostWriter. If the submission fails, or if the config specifies all logs should be saved, the `Entry` is passed to the `save_log()` function which saves it as a JSON object. 55 | 56 | #### Entry 57 | 58 | The `Entry` class is mostly responsible for encapsulating data as it's passed around the application but contains some logic to normalize and return it in different formats for the distinct REST and GraphQL APIs. 59 | 60 | ### Clients 61 | 62 | The current clients, written using Bash and PowerShell, are integrated into their respective hook code and implement similar logic. They define client-side configuration settings at the top, include functions to enable/disable hooking and control verbosity, and define the hook functions themselves. The hook functions capture the raw data such as the executed command and timestamps, as well as operator and source host if the environment variables are set. This data is then packaged as a JSON object and sent to the server. The response is received and optionally printed, depending on the verbosity settings. 63 | 64 | The Bash client uses [bash-preexec](https://github.com/rcaloras/bash-preexec) to create the `preexec` and `precmd` (i.e., post-exec) hook points and uses `jq` to construct and parse the JSON objects exchanged with the server. 65 | 66 | The PowerShell client overrides the `PSConsoleHostReadLine` and `Prompt` functions to create pre-exec and post-exec hooks. 67 | 68 | --- 69 | 70 | ### Execution Flow 71 | 72 | The terminal_sync server is started by executing `python -m terminal_sync` either directly or by running `pdm serve`. This runs the `__main__.py` module, which parses any host and port arguments and calls the `run()` function in `api.py`. When `api.py` is loaded, it instantiates a `Config` object, a `GhostWriterClient` object, and an instance of FastAPI. The `run()` method starts uvicorn to host the FastAPI instance. 73 | 74 | When a user runs a command, the client hook code intercepts it, packages the command with additional metadata (including a UUID), and sends it to the creation endpoint on the terminal_sync server. The `pre_exec()` function calls `log_command()`, which checks whether the command contains any of the configured keywords. If so, a new `Entry` object is created, added to an internal buffer, and sent to the `create_log()` method of the GhostWriter client. The GhostWriter client then uses either `_create_entry_graphql()` or `_create_entry_rest()`, depending on which API key was specified, to send the command data to GhostWriter. If succcessful, GhostWriter returns a JSON object containing the ID of the GhostWriter log entry. The GhostWriter client passes this ID back to `log_command()` where it is added to the `Entry` object. The `Entry` object and a success message are returned to the `pre_exec()` function, triggering the `finally` clause in `log_command()`. If the connection to GhostWriter had failed or if the application is configured to save all logs, `log_command()` will call `save_log()` to write the `Entry` data to a JSON file. Back in `pre_exec()`, the message is returned to the terminal_sync client. The terminal_sync client optionally displays the message, depending on the verbosity settings, and returns, allowing the command to execute. 75 | 76 | When the command completes, the client hook code intercepts execution again, records the exit status of the command, retrieves additional information about the command from the shell history, packages it all up, and sends it to the update endpoint on the terminal_sync server. The `post_exec()` function calls `log_command()`, which uses the UUID string sent with the command to retrieve the previously created `Entry` object from the internal buffer. The `Entry` is updated and sent to the GhostWriter client's `update_log()` method, which maps to either `_update_entry_graphql()` or `_update_entry_rest()`. The remainder of the flow is essentially identical to the creation flow, except, when execution returns to `post_exec()`, the `Entry` is removed from the internal buffer, since it has been processed. 77 | -------------------------------------------------------------------------------- /docs/developer_guide.md: -------------------------------------------------------------------------------- 1 | # Developer Guide 2 | 3 | Thank you for your interest in contributing to terminal_sync! 4 | 5 | If you haven't already done so, we recommend you start by learning [how terminal_sync has evolved](architecture.md#design-evolution) and [how terminal_sync currently works](architecture.md#how-terminal_sync-works). This will help explain some of the design decisions and orient you to the codebase. 6 | 7 | When you're ready to start coding, you'll follow this general process: 8 | 9 | 1. Fork the repo 10 | 2. Clone your fork 11 | 3. [Setup your environment](#setting-up-your-environment) 12 | 1. Install PDM 13 | 2. Use PDM to install all dependencies 14 | 3. Install pre-commit 15 | 4. Write code or make changes 16 | 5. Write tests 17 | 6. [Run tests](#pytest) 18 | 7. Update [documentation](#documentation) and the CHANGELOG 19 | 8. Commit code (...fix any [pre-commit](#pre-commit) failures, re-add, and re-commit code) 20 | 9. Submit a pull request 21 | 22 | --- 23 | 24 | ## Tools 25 | 26 | - Git 27 | - Python 3.10+ and pip 28 | - [PDM](https://pdm.fming.dev/latest/) 29 | - This is a package dependency manager and general project management utility, similar to Poetry 30 | - [pre-commit](https://pre-commit.com/) 31 | - A framework for managing multi-language pre-commit hooks 32 | - This is used to automate tedious tasks and enforce consistent standards 33 | - Code editor 34 | - [Visual Studio Code](https://code.visualstudio.com/) with the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) (recommended) 35 | 36 | --- 37 | 38 | ## Setting Up Your Environment 39 | 40 | ### PDM 41 | 42 | ```bash 43 | # Install PDM 44 | pip install pdm 45 | 46 | # Install all dependencies 47 | pdm install 48 | 49 | # Install pre-commit hooks 50 | pdm run pre-commit install 51 | ``` 52 | 53 | Use `pdm list` to display a list of installed dependencies and their versions or `pdm list --graph` to display this information in tree format with sub-dependencies appropriately nested. 54 | 55 | ### Integrated Development Environment (IDE) 56 | 57 | While it's not required, we recommend using Visual Studio Code (VS Code) as your IDE. To configure VS Code, create a file named `terminal_sync.code-workspace` in the root project directory. Add the following to it, then run `pdm code`. This will start your VS Code instance within the PDM environment, allowing it to find locally installed packages without additional configuration. 58 | 59 | ```json 60 | { 61 | "folders": [ 62 | { 63 | "path": "." 64 | } 65 | ], 66 | "settings": { 67 | "python.defaultInterpreterPath": ".\\.venv\\Scripts\\python.exe" 68 | } 69 | } 70 | ``` 71 | 72 | While developing, you'll typically run the server through your IDE to enable features like the debugger; however, if you need to start the server from command-line, use `pdm serve` or `pdm run python -m terminal_sync`. 73 | 74 | ### pytest 75 | 76 | To run tests, use `pdm test` or `pdm run pytest`. 77 | 78 | ### pre-commit 79 | 80 | pre-commit, as the name may suggest, only checks files that are tracked by git; be sure to `git add` any relevant files before running the checks. 81 | 82 | The pre-commit configuration and hooks are contained in `.pre-commit-config.yaml`. 83 | 84 | By default, pre-commit will run when you make a commit; however, you can also run the checks manually using `pdm check` or `pdm run pre-commit run --all-files`. 85 | 86 | ### Documentation 87 | 88 | The terminal_sync documentation is written in Markdown, located under `docs/`, built using `mkdocs`, hosted using GitHub Pages, and automatically deployed using a GitHub Actions workflow (`.github/workflows/documentation.yml`). 89 | 90 | To view the documentation locally, run `pdm docs` or `pdm run mkdocs serve [--dev-addr :]`. 91 | 92 | ## Conventions 93 | 94 | Whenever possible, use `pyproject.toml` for all external tool configurations, including pre-commit hooks. This centralizes the configuration settings and ensures consistency in case developers run the same tool manually and with pre-commit. 95 | 96 | Please refer to the [Style Guide](style_guide.md) for stylistic conventions. 97 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # terminal_sync 2 | 3 | ## Overview 4 | 5 | terminal_sync is a standalone tool for logging Bash and PowerShell commands to [GhostWriter](https://github.com/GhostManager/Ghostwriter) automatically. The provided Bash script and PowerShell module register pre-exec and post-exec hooks that capture and send information about executed commands to the terminal_sync server for additional processing and enrichment. Once properly configured, any commands that meet the configured logging criteria (e.g., contain a specific keyword) are sent to GhostWriter. 6 | 7 | --- 8 | 9 | ## Features 10 | 11 | - **Automatic Shell Logging** 12 | - Logs Bash and PowerShell commands directly to GhostWriter based on a configurable keyword list 13 | 14 | - **Export Log Entries to CSV** 15 | - Saves failed (or optionally all) command log entries to JSON files that can be [converted to CSV](usage.md#export-logs-to-ghostwriter-csv) and imported into GhostWriter 16 | - Supports off-line logging 17 | 18 | - **Command Timestamps** 19 | - Displays execution and completion timestamps for each command 20 | - Useful reference for commands not configured to auto-log 21 | 22 | - **In-line Descriptions** 23 | - Supports [adding a description](usage.md#add-a-description) to the end of a command 24 | - Allows users to [force an individual command to be logged](usage.md#log-ad-hoc-commands) 25 | - Maintains flow by keeping users at the command-line 26 | 27 | - **Simple Configuration** 28 | - Easy [setup and configuration using YAML config file and/or environment variables](setup.md#2-configure-the-server) 29 | 30 | - **Management Commands** 31 | - Ability to [enable/disable terminal_sync](usage.md#enable--disable-terminal_sync) or [change the verbosity](usage.md#adjust-console-output-at-runtime) for an individual session 32 | 33 | --- 34 | 35 | ## Known Limitations 36 | 37 | - Background jobs (i.e., Bash commands ending with `&` and PowerShell `Start-Job` commands) will always be reported as successful since the post-exec hook runs when the prompt returns, which happens before the command completes. 38 | 39 | ### Bash Limitations 40 | 41 | - Compound commands (i.e., multiple commands joined by `&&`) run in the background will not be logged 42 | - These commands trigger the `precmd` (i.e., post-exec) hook but not the `preexec` hook; however, the current post-exec implementation relies on a variable set in the pre-exec hook to prevent logging duplicate entries when a user submits an empty line 43 | 44 | --- 45 | 46 | ## Local vs Remote Usage 47 | 48 | The terminal_sync server is intended to be run locally and therefore does not include authentication or encryption. Should you choose to run the server on a remote host, it is highly recommended that you run it on `localhost` and use an SSH forward tunnel, or similar mechanism, to access it. 49 | 50 | Similarly, terminal_sync was (mostly) designed with a single user per instance in mind. The one exception is that if the `OPERATOR` environment variable is set within a client shell session, this value will override the operator setting on the server, thus allowing multiple users to share a terminal_sync server. That said, the server itself only supports a single API key / token per instance, so make sure all users with access to the server are authorized for that level of access to GhostWriter. 51 | -------------------------------------------------------------------------------- /docs/quickstart.md: -------------------------------------------------------------------------------- 1 | # Quickstart 2 | 3 | The following sections provide the minimum steps required to configure terminal_sync without all those pesky explanations. If you encounter problems or want additional details, please refer to the [Setup](setup.md) page. 4 | 5 | These directions assume: 6 | 7 | 1. You have the following software installed: 8 | - Git 9 | - Python 3.10+ and pip **OR** Docker and Docker Compose 10 | 2. You will be running the terminal_sync server locally 11 | 3. You will be capturing commands from a local Bash session on Linux or a local PowerShell session on Windows 12 | 13 | ```bash 14 | # Step 1: Get the Code 15 | git clone https://github.com/breakid/terminal_sync 16 | cd terminal_sync 17 | 18 | # Step 2: Configure the Server 19 | cp config_template.yaml config.yaml 20 | # ACTION: Modify the gw_url, gw_oplog_id, and gw_api_key_graphql or 21 | # gw_api_key_rest settings to match your environment 22 | 23 | # Step 3: Run the Server 24 | 25 | # Step 3a: Docker 26 | touch terminal_sync.log # On Linux 27 | $null > terminal_sync.log # On Windows 28 | docker-compose up -d 29 | 30 | # Step 3b: PDM 31 | pip install pdm 32 | pdm install --prod 33 | pdm serve 34 | 35 | # Step 4: Setup Terminal Hooks 36 | 37 | # Bash: 38 | source terminal_sync.sh 39 | # ACTION: Answer the prompts that appear on first run 40 | 41 | # PowerShell: 42 | Import-Module terminal_sync.psm1 43 | ``` 44 | -------------------------------------------------------------------------------- /docs/setup.md: -------------------------------------------------------------------------------- 1 | # Setup 2 | 3 | ## Introduction 4 | 5 | The following is a high-level overview of the steps required to setup terminal_sync. Additional details are provided in the sections below. 6 | 7 | 1. [Get the Code](#1-get-the-code) 8 | 2. [Configure the Server](#2-configure-the-server) 9 | 3. [Run the Server](#3-run-the-server) 10 | - [Docker](#docker) 11 | - [PDM](#pdm) 12 | 4. [Setup Terminal Hooks](#4-setup-terminal-hooks) 13 | - [Bash](#bash) 14 | - [PowerShell](#powershell) 15 | 16 | If you encounter problems, please refer to the [Troubleshooting](troubleshooting.md) page. 17 | 18 | **Prerequisites**: These instructions assume you have either Python 3.10+ and pip or Docker and Docker Compose installed. 19 | 20 | --- 21 | 22 | ## 1. Get the Code 23 | 24 | Use `git` to clone this repo, or download and extract a zip archive of the files. 25 | 26 | ```bash 27 | git clone https://github.com/breakid/terminal_sync 28 | cd terminal_sync 29 | ``` 30 | 31 | All subsequent instructions are provided from the context of the root project directory. 32 | 33 | --- 34 | 35 | ## 2. Configure the Server 36 | 37 | The server can be configured using a YAML config file, environment variables, or a combination thereof, with environment variables overriding config file values. By default, terminal_sync will look for `config.yaml` in the current working directory (relative to where you run the server). You may use the `TERMSYNC_CONFIG` environment variable to specify an alternate config file path. 38 | 39 | An example configuration file, `config_template.yaml`, is provided and contains comments that explain the purpose of each setting. To create a new config file, we recommend that you copy this template and edit the copy to meet your needs. 40 | 41 | ```bash 42 | cp config_template.yaml config.yaml 43 | ``` 44 | 45 | Environment variables match the upper-case version (on case-sensitive systems) of the setting name found in the config file. For instance, the config file settings `gw_url` and `gw_oplog_id` become the environment variables `GW_URL` and `GW_OPLOG_ID`. The values are parsed as YAML, so all options found in the config file are supported, including complex structures such as lists and dictionaries. 46 | 47 | The server will automatically load any environment variables defined in a `.env` file. 48 | 49 | At a minimum, the `gw_url`, `gw_oplog_id`, and at least one of `gw_api_key_graphql` or `gw_api_key_rest` must be configured for terminal_sync to log to GhostWriter. If both API keys are set, terminal_sync will use GraphQL by default. 50 | 51 | **Note**: To allow terminal_sync to be used off-line or independent of GhostWriter, the server will display a warning but _**start successfully**_ even if these values are not provided. In this case, local logging will be enabled by default. 52 | 53 | --- 54 | 55 | ## 3. Run the Server 56 | 57 | The server can be run as a Docker container or using [PDM](https://pdm.fming.dev/latest/). 58 | 59 | ### Docker 60 | 61 | While there is not currently a pre-built image, a `Dockerfile` and `docker-compose.yaml` config are provided to simplify the build process. The default Compose config assumes: 62 | 63 | 1. You created a `config.yaml` file in the previous step 64 | 2. You have a `terminal_sync.log` file in the root project directory 65 | - This will be bind mounted into the container to persist application logs 66 | - Use `touch terminal_sync.log` in Bash or `$null > terminal_sync.log` in PowerShell to initialize this file 67 | 68 | If you prefer to use environment variables rather than a config file, uncomment the `environment` section, fill in the appropriate values, and comment out or remove the `config.yaml` volume entry. 69 | 70 | **Note**: If the `config.yaml` or `terminal_sync.log` files do not exist, Compose will create an empty directory for each missing source path. If you choose not to use these volumes, comment out or remove them from the Compose config. 71 | 72 | Once you have made any desired modifications to the Compose config, use the following command to start the server, optionally in detached mode (`-d`). On first run, Docker Compose should automatically build a local copy of the image, which will be used for subsequent executions. 73 | 74 | ```bash 75 | docker-compose up -d 76 | ``` 77 | 78 | If you need to rebuild the image, such as after making or pulling changes to the code, add the `--build` flag to the command. 79 | 80 | ```bash 81 | docker-compose up -d --build 82 | ``` 83 | 84 | When running in detached mode, you won't see any output from the container. Use the following command to view the logs; this is especially useful for troubleshooting. 85 | 86 | ```bash 87 | docker-compose logs 88 | ``` 89 | 90 | If the build fails, you may need to build the image manually using Docker. 91 | 92 | ```bash 93 | docker build --network=host --tag=terminal_sync:latest . 94 | ``` 95 | 96 | To stop the server, run the following: 97 | 98 | ```bash 99 | docker-compose down 100 | ``` 101 | 102 | ### PDM 103 | 104 | If you have Python 3.10 or later, you can run the server using PDM. 105 | 106 | ```bash 107 | # Install PDM 108 | pip install pdm 109 | 110 | # Use PDM to install the production dependencies and terminal_sync package 111 | pdm install --prod 112 | 113 | # Use the PDM 'serve' script to run the application with uvicorn 114 | # Note: This will run the server in the foreground, occupying your terminal 115 | pdm serve 116 | ``` 117 | 118 | To stop the server, press `CTRL+C`. If that doesn't work, kill the `uvicorn` process manually. 119 | 120 | --- 121 | 122 | ## 4. Setup Terminal Hooks 123 | 124 | ### Bash 125 | 126 | 1. Review and optionally edit the **Configuration Settings** section at the top of `terminal_sync.sh` 127 | 2. Run `source ./terminal_sync.sh` 128 | - **Note**: This must be done in each new bash session 129 | - You will be prompted to install any missing dependencies 130 | - On first run, you will also be prompted whether you want to install the hooks (i.e., automatically source the script in each new session) 131 | 132 | If you decide later that you want to install the hooks, just append `source '/terminal_sync.sh'` to your `~/.bashrc` file. 133 | 134 | ### PowerShell 135 | 136 | 1. Review and optionally edit the **Configuration Settings** section at the top of `terminal_sync.psm1` 137 | 2. Run `Import-Module terminal_sync.psm1` 138 | - **Note**: This must be done in each new PowerShell session 139 | - If this fails, you may need to use `Set-ExecutionPolicy` to allow scripts 140 | 141 | If you want to load the module automatically, run the following: 142 | 143 | ```bash 144 | # Set the execution policy to allow scripts to run 145 | # Alternatively, you can set the policy to 'Bypass' to disable all warnings 146 | Set-ExecutionPolicy Unrestricted -Scope CurrentUser 147 | 148 | # Add terminal_sync.psm1 to your PowerShell profile so it will be loaded automatically 149 | Write-Output "Import-Module '$(Resolve-Path terminal_sync.psm1)'" | Out-File -Append -Encoding utf8 $PROFILE 150 | ``` 151 | -------------------------------------------------------------------------------- /docs/style_guide.md: -------------------------------------------------------------------------------- 1 | # Style Guide 2 | 3 | Consistent style is important for clean and maintainable code. Unless contradicted by the guidance below, all contributors should follow [PEP 8 – Style Guide for Python Code](https://peps.python.org/pep-0008/) and any other applicable PEP standards. 4 | 5 | Additionally, this project uses a variety of [pre-commit](https://pre-commit.com/) hooks to automatically lint, format, and otherwise clean up code. Pull requests will not be accepted unless the pre-commit checks pass or convincing justification is provided. 6 | 7 | --- 8 | 9 | ## Line Length 10 | 11 | Lines should be 120 characters or less. 12 | 13 | We are no longer technologically limited to 80 characters per line. A 120 character limit works well with modern tools, improves readability, and makes better use of horizontal screen space, allowing developers to see more code at once. 14 | 15 | ## Imports 16 | 17 | Most imports should be placed at the top of the file as stated in PEP 8; however, third-party packages may be imported within the code if they are part of an optional and non-critical workflow. Users should not be required to install unnecessary packages if they don't intend to use the associated functionality, and the program should function properly without these optional packages. 18 | 19 | Each import should be on a separate line to minimize merge conflicts (see [reorder_python_imports](https://github.com/asottile/reorder_python_imports#why-this-style)). 20 | 21 | Imports should be grouped into (at least) three sections: Standard Libraries, Third-party Libraries, and Internal Libraries. This is enforced by the `isort` pre-commit hook. 22 | 23 | ## Comments 24 | 25 | terminal_sync uses Google Style docstrings. Click [here](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) for some examples. 26 | -------------------------------------------------------------------------------- /docs/troubleshooting.md: -------------------------------------------------------------------------------- 1 | # Troubleshooting 2 | 3 | The following is a list of potential errors identified during testing and recommended methods for resolving them. 4 | 5 | --- 6 | 7 | ## Test Environments 8 | 9 | Development and testing were performed using the configurations listed below. If you encounter any problems attributable to a different environment, please [submit a GitHub issue](https://github.com/breakid/terminal_sync/issues); be sure to include a detailed description of the problem and relevant information about your environment. We can't fix what we can't replicate. 10 | 11 | - Windows 11 (terminal_sync server and PowerShell hooks) 12 | - Docker 20.10.24, build 297e128 13 | - Docker Compose v2.17.2 14 | - PowerShell 5.1.22621.963 15 | - Python 3.11 16 | - Debian 11 (terminal_sync server and Bash hooks) 17 | - Docker version 23.0.4, build f480fb1 18 | - Docker Compose version v2.17.2 19 | - Python 3.11.3 20 | - Debian 11 (Bash hooks) 21 | - Python 3.9.2 22 | - GhostWriter running over HTTPS 23 | 24 | --- 25 | 26 | ## Server Problems 27 | 28 | ### No GhostWriter API key specified 29 | 30 | **Problem**: Neither a GraphQL nor a REST API key were provided 31 | 32 | **Solution**: Make sure to enter a valid API key for at least one of these settings in the `config.yaml` file or set the `GW_API_KEY_GRAPHQL` or `GW_API_KEY_REST` environment variables. 33 | 34 | ### A `config.yaml` or `terminal_sync.log` directory gets created 35 | 36 | **Problem**: You didn't create the necessary file(s) before running the server with Docker Compose 37 | 38 | **Solution**: 39 | 40 | 1. Stop the server (`docker-compose down`) 41 | 2. Delete the `config.yaml` and/or `terminal_sync.log` directory 42 | 3. Initalize the `config.yaml` and/or `terminal_sync.log` files (see [Setup: Configure the Server](setup.md#2-configure-the-server)) 43 | 4. Restart the server (`docker-compose up -d`) 44 | 45 | --- 46 | 47 | ## Client Problems 48 | 49 | ### Cannot connect to host ssl:False [getaddrinfo failed] 50 | 51 | **Problem**: terminal_sync is unable to resolve the hostname of your GhostWriter server 52 | 53 | **Solution**: 54 | 55 | 1. Verify the `gw_url` setting contains the correct hostname 56 | 2. Verify connectivity to your GhostWriter server (e.g., check any VPNs, SSH tunnels, etc.) 57 | 3. Check your DNS settings 58 | 59 | --- 60 | 61 | ### Cannot connect to host ssl:False [The remote computer refused the network connection] 62 | 63 | **Problem**: terminal_sync can reach the GhostWriter server, but the port is blocked 64 | 65 | **Solution**: 66 | 67 | 1. Verify the `gw_url` setting contains any applicable port numbers 68 | 2. Check the firewall settings on your GhostWriter server 69 | 70 | --- 71 | 72 | ### Authentication hook unauthorized this request 73 | 74 | **Problem**: Your GraphQL token is invalid 75 | 76 | **Solution**: 77 | 78 | 1. Verify your token hasn't expired 79 | 2. Verify the token you specified is correct and complete 80 | 3. Generate a new GraphQL token key 81 | 82 | --- 83 | 84 | ### check constraint of an insert/update permission has failed 85 | 86 | **Problem**: You're using the GraphQL API, and either the Oplog ID you're trying to write to doesn't exist, or you don't have permission to write to it 87 | 88 | **Solution**: 89 | 90 | 1. Verify an Oplog with the specified ID exists 91 | 2. Verify your user account is assigned to the project to which the specified Oplog belongs 92 | 93 | --- 94 | 95 | ### Authentication credentials were not provided 96 | 97 | **Problem**: You're using the REST API and provided an API key, but your `gw_url` is using `http://` rather than `https://` 98 | 99 | **Solution**: Modify your `gw_url` to use `https://` 100 | 101 | --- 102 | 103 | ### 404, message='Not Found', url=URL('https:///v1/graphql') 104 | 105 | **Problem**: While there are likely many causes for this generic issue, this was observed when using the GraphQL API and a `gw_url` containing `http://` rather than `https://` 106 | 107 | **Solution**: Modify your `gw_url` to use `https://` 108 | -------------------------------------------------------------------------------- /docs/updating.md: -------------------------------------------------------------------------------- 1 | # Updating terminal_sync 2 | 3 | 1. Use `git pull` to get the latest updates or download an updated zip archive from GitHub 4 | 2. Update the server 5 | - If using Docker, run `docker-compose up -d --build` to rebuild the image 6 | - If using Python, run `pdm install --prod` to install any new or updated packages 7 | 3. Update any installed terminal hooks 8 | 1. Overwrite the previous script / module file with the updated version (if the `git pull` didn't do this automatically); be sure to update the new script / module with any configuration changes you made to the old one 9 | 2. Start a new shell session 10 | -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | # Usage 2 | 3 | The entire point of terminal_sync is to log shell commands automatically. Therefore, once the [server is setup and the hooks are registered](setup.md), no further action is necessary. That said, the following are a few runtime options that can enhance the user experience. 4 | 5 | --- 6 | 7 | ## Specify the Source Host 8 | 9 | Set the environment variable `SRC_HOST` to the host where your activity will originate. This value will appear in the Source field on GhostWriter and is particularly useful when operating over a SOCKS proxy or tunnel. If the client (i.e., hook) environment is different than the terminal_sync server environment (e.g., if using Docker), the client-side value will override the server-side value. 10 | 11 | If this value is not provided, terminal_sync will default to the hostname and IP of the host where the server is running. If using Docker, this will be the container. 12 | 13 | ## Add a Description 14 | 15 | terminal_sync allows users to (optionally) specify a description at the end of each command. Anything that appears after the string specified by the `gw_description_token` setting will be extracted and used as the Description attribute of the log entry. 16 | 17 | **Note**: This token must begin with a `#` so that Bash and PowerShell interpret it, and everything that follows, as a comment and don't attempt to execute the description text. 18 | 19 | ## Log Ad-hoc Commands 20 | 21 | Since the `gw_description_token` inherently triggers logging, users can append this string to any command, with or without additional text, to force an individual command to be logged. 22 | 23 | ## Enable / Disable terminal_sync 24 | 25 | Run `Disable-TermSync` to temporarily disable terminal_sync once hooks are registered for that session. To re-enable it, run `Enable-TermSync`. These commands set a flag that is checked when each hook is run, skipping the hook logic if disabled, and consequently only affect the current session. 26 | 27 | To permanently disable terminal_sync, delete or comment out the line in `~/.bashrc` or your PowerShell `$PROFILE` that loads the hooks. 28 | 29 | ## Adjust Console Output at Runtime 30 | 31 | Both the Bash script and PowerShell module contain a configuration setting that allows users to set the default console output; however, this can be changed (temporarily) for a session, using the `Set-TermSyncVersbosity` command. 32 | 33 | In Bash, simply run `Set-TermSyncVersbosity`; this will print a list of display settings and prompt you for a number. Enter the number that matches your preferred setting. 34 | 35 | In PowerShell, type `Set-TermSyncVerbosity`, followed by a space, then press **Tab** to cycle through the available options. Press **Enter** to select your preferred setting. 36 | 37 | ## Export Logs to GhostWriter CSV 38 | 39 | Any log entries that cannot be sent to GhostWriter successfully, such as due to a configuration or connectivity issue, will be saved (local to the server) in JSON format. The configuration setting `termsync_save_all_local` can be used to override this behavior and save all entries, even those logged to GhostWriter successfully. If the GhostWrite URL or API keys are not provided, this setting is automatically enabled to prevent accidental loss of logs. 40 | 41 | On shutdown, the terminal_sync server will attempt to export these saved logs to a timestamped CSV file that can be imported to GhostWriter. The `export_csv.py` script can also be run manually to generate a CSV file without stopping the server. 42 | 43 | ```bash 44 | # Usage: 45 | # export_csv.py [-h] -l LOG_DIR [-o OUTPUT_DIR] 46 | 47 | # Example: 48 | python src/terminal_sync/export_csv.py -l log_archive 49 | ``` 50 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: terminal_sync 2 | site_url: https://breakid.github.io/terminal_sync/ 3 | theme: readthedocs 4 | nav: 5 | - Home: index.md 6 | - Getting Started: 7 | - Quickstart: quickstart.md 8 | - Setup: setup.md 9 | - Usage: usage.md 10 | - Updating: updating.md 11 | - Troubleshooting: troubleshooting.md 12 | - Development: 13 | - Architecture: architecture.md 14 | - Developer Guide: developer_guide.md 15 | - Style Guide: style_guide.md 16 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["pdm-backend"] 3 | build-backend = "pdm.backend" 4 | 5 | [project] 6 | name = "terminal_sync" 7 | version = "0.3.0" 8 | description = "A standalone tool for logging shell commands to GhostWriter automatically" 9 | authors = [{ name = "breakid" }] 10 | license = { text = "GPL-3.0-or-later" } 11 | readme = "README.md" 12 | requires-python = ">=3.10" # The type hinting used in this project follows PEP 604, which was implemented in 3.10 13 | dependencies = [ 14 | "aiohttp>=3.8.4", 15 | "fastapi>=0.95.0", 16 | "gql>=3.4.0", 17 | "python-dotenv>=1.0.0", 18 | "pyyaml>=6.0", 19 | "uvicorn>=0.21.1", 20 | ] 21 | keywords = ["GhostWriter"] 22 | 23 | [project.urls] 24 | homepage = "https://github.com/breakid/terminal_sync" 25 | documentation = "https://breakid.github.io/terminal_sync" 26 | repository = "https://github.com/breakid/terminal_sync" 27 | 28 | [tool.black] 29 | line-length = 120 30 | 31 | [tool.flake8] 32 | # Compatibility settings for Black (see https://black.readthedocs.io/en/latest/guides/using_black_with_other_tools.html#flake8) 33 | extend-ignore = ["E203"] 34 | max-line-length = 120 35 | 36 | [tool.interrogate] 37 | exclude = ["docs", "build"] 38 | fail-under = 90 39 | ignore-init-method = true 40 | ignore-init-module = true 41 | verbose = 2 42 | 43 | [tool.isort] 44 | atomic = true 45 | force_single_line = true 46 | import_headings = { stdlib = "Standard Libraries", thirdparty = "Third-party Libraries", firstparty = "Internal Libraries" } 47 | known_first_party = ["terminal_sync"] 48 | line_length = 120 49 | profile = "black" 50 | 51 | [tool.mypy] 52 | disable_error_code = "attr-defined" 53 | 54 | [tool.pdm] 55 | 56 | [tool.pdm.dev-dependencies] 57 | dev = [ 58 | "black>=23.3.0", 59 | "pytest>=7.3.0", 60 | "pre-commit>=3.2.2", 61 | "types-PyYAML>=6.0.12.9", 62 | ] 63 | docs = ["mkdocs>=1.4.2"] 64 | 65 | [tool.pdm.scripts] 66 | check = "pre-commit run --all-files" 67 | code = "code terminal_sync.code-workspace" 68 | # Run the documentation server on 8080 so it doesn't interfere with the terminal_sync server 69 | docs = "mkdocs serve --dev-addr 127.0.0.1:8080" 70 | serve = "python -m terminal_sync" 71 | test = "pytest" 72 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # This file is @generated by PDM. 2 | # Please do not edit it manually. 3 | 4 | aiohttp==3.8.4 5 | aiosignal==1.3.1 6 | anyio==3.6.2 7 | async-timeout==4.0.2 8 | attrs==22.2.0 9 | backoff==2.2.1 10 | charset-normalizer==3.1.0 11 | click==8.1.3 12 | colorama==0.4.6 13 | fastapi==0.95.1 14 | frozenlist==1.3.3 15 | gql==3.4.0 16 | graphql-core==3.2.3 17 | h11==0.14.0 18 | idna==3.4 19 | multidict==6.0.4 20 | pydantic==1.10.7 21 | python-dotenv==1.0.0 22 | pyyaml==6.0 23 | sniffio==1.3.0 24 | starlette==0.26.1 25 | typing-extensions==4.5.0 26 | uvicorn==0.21.1 27 | yarl==1.8.2 28 | -------------------------------------------------------------------------------- /src/terminal_sync/__init__.py: -------------------------------------------------------------------------------- 1 | """Marks the current directory as a Python package""" 2 | 3 | # Note: Version is also defined in pyproject.toml. Ideally, to ensure they don't get out of sync, version would 4 | # only be defined once; however, the project one is only accessible if terminal_sync is installed as a package 5 | __version__ = "0.3.0" 6 | -------------------------------------------------------------------------------- /src/terminal_sync/__main__.py: -------------------------------------------------------------------------------- 1 | """Executes the terminal_sync server when the module is run""" 2 | 3 | # Standard Libraries 4 | from argparse import ArgumentParser 5 | 6 | # Internal Libraries 7 | from terminal_sync.api import run 8 | 9 | parser = ArgumentParser() 10 | parser.add_argument("--host", dest="host", default="127.0.0.1", help="The host address where the server will bind") 11 | parser.add_argument("--port", dest="port", default=8000, type=int, help="The host port where the server will bind") 12 | args = parser.parse_args() 13 | 14 | run(host=args.host, port=args.port) 15 | -------------------------------------------------------------------------------- /src/terminal_sync/api.py: -------------------------------------------------------------------------------- 1 | """A REST API server for logging terminal commands to GhostWriter""" 2 | 3 | # Standard Libraries 4 | import json 5 | import logging 6 | import sys 7 | from asyncio.exceptions import TimeoutError 8 | from datetime import datetime 9 | from os import getenv 10 | from os import makedirs 11 | from pathlib import Path 12 | from re import match 13 | from time import gmtime 14 | 15 | # Third-party Libraries 16 | from fastapi import FastAPI 17 | from fastapi import HTTPException 18 | from fastapi import status 19 | from gql.transport.exceptions import TransportQueryError 20 | from graphql.error.graphql_error import GraphQLError 21 | from pydantic import BaseModel 22 | 23 | # Internal Libraries 24 | from terminal_sync.config import Config 25 | from terminal_sync.export_csv import export_csv 26 | from terminal_sync.ghostwriter import GhostWriterClient 27 | from terminal_sync.log_entry import Entry 28 | 29 | # ============================================================================= 30 | # ****** Logging ***** 31 | # ============================================================================= 32 | 33 | # Create a handler that outputs to the console (stderr by default) 34 | # Use `logging.StreamHandler(sys.stdout)` to output to stdout instead 35 | console_handler = logging.StreamHandler() 36 | console_handler.setLevel(logging.INFO) 37 | console_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] - %(message)s")) 38 | 39 | # Create a file handler for detailed debug logs 40 | file_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(funcName)s - %(message)s") 41 | file_formatter.converter = gmtime # Use UTC timestamps 42 | 43 | file_handler = logging.FileHandler("terminal_sync.log") 44 | file_handler.setFormatter(file_formatter) 45 | file_handler.setLevel(logging.DEBUG) 46 | 47 | # Create a logger 48 | logging.basicConfig( 49 | # Note: You must set the global logging level to the most inclusive setting you want to log; individual handlers 50 | # can limit the level but not increase it 51 | level=logging.NOTSET, 52 | handlers=[file_handler, console_handler], 53 | ) 54 | logger = logging.getLogger("terminal_sync") 55 | 56 | gw_client: GhostWriterClient | None = None 57 | 58 | try: 59 | # Get config settings from defaults, config file, and environment variables 60 | config = Config() 61 | 62 | # If no API key specified, skip creating the client 63 | # This allows terminal_sync to be used for local logging without a GhostWriter instance 64 | if config.gw_url and (config.gw_api_key_graphql or config.gw_api_key_rest): 65 | # Create a GhostWriter client using config settings 66 | gw_client = GhostWriterClient( 67 | url=config.gw_url, 68 | graphql_api_key=config.gw_api_key_graphql, 69 | rest_api_key=config.gw_api_key_rest, 70 | timeout_seconds=config.termsync_timeout_seconds, 71 | ) 72 | except Exception as e: 73 | logger.exception(e) 74 | sys.exit(1) 75 | 76 | 77 | # ============================================================================= 78 | # ****** API Server ***** 79 | # ============================================================================= 80 | 81 | app = FastAPI() 82 | 83 | 84 | class Message(BaseModel): 85 | """Defines a Message class that encapsulates the log entry data passed from a client 86 | 87 | Used to force FastAPI to pass the data through the request body rather than as query parameters 88 | """ 89 | 90 | command: str 91 | comments: str | None = None 92 | description: str | None = None 93 | gw_id: int | None = None 94 | operator: str | None = config.operator 95 | oplog_id: int = config.gw_oplog_id 96 | output: str | None = None 97 | source_host: str | None = getenv("SRC_HOST") 98 | start_time: datetime = datetime.utcnow() 99 | end_time: datetime = datetime.utcnow() 100 | uuid: str = "" 101 | 102 | 103 | # Dictionary used to store a mapping of UUIDs to log entries 104 | # This allows terminal_sync to lookup and updated previous log entries when the command completes 105 | log_entries: dict[str, Entry] = {} 106 | 107 | 108 | async def save_log(uuid: str, entry: Entry) -> None: 109 | """Save the entry to a JSON file 110 | 111 | By default, used to cache entries if they fail to log to GhostWriter but can be enabled for all logs 112 | 113 | Args: 114 | uuid (str): A universally unique identifier for the entry 115 | entry (Entry): The entry to be saved 116 | """ 117 | logger.debug(f'Saving log with UUID "{uuid}": {entry}') 118 | 119 | # Make sure the output directory exists 120 | makedirs(config.termsync_json_log_dir, exist_ok=True) 121 | 122 | # Write updated dictionary back to disk 123 | with open(Path(config.termsync_json_log_dir) / entry.json_filename(), "w") as out_file: 124 | json.dump(entry.gw_fields(), out_file) 125 | 126 | 127 | async def log_command(msg: Message) -> tuple[Entry, str]: 128 | """Create and/or return a GhostWriter log entry object 129 | 130 | Checks whether the command in the specified message should trigger logging 131 | If so, return an existing entry or create a new entry if a matching one does not exist 132 | 133 | Args: 134 | msg (Message): An object containing command information sent by a client 135 | 136 | Returns: 137 | tuple[Entry, str]: A tuple containing the entry with updated gw_id and a message to display to the user 138 | 139 | Raises: 140 | HTTPException: If the command didn't trigger logging or an error occurred while communicating with GhostWriter 141 | """ 142 | error_msg: str 143 | 144 | # Check whether any of the keywords that trigger logging appear in the command 145 | if any(keyword in msg.command for keyword in config.termsync_keywords): 146 | # Flag used to determine whether the entry was logged successfully 147 | # If not, the 'finally' clause will save the log locally 148 | saved: bool = False 149 | 150 | try: 151 | # Parse the description from the command, if applicable 152 | if config.gw_description_token in msg.command: 153 | (msg.command, msg.description) = msg.command.split(config.gw_description_token) 154 | 155 | # Try to lookup an existing entry by UUID 156 | entry: Entry | None = log_entries.get(msg.uuid) 157 | 158 | if entry: 159 | # Update the existing entry using msg attributes 160 | entry.update(dict(msg)) 161 | else: 162 | # Scenarios: 163 | # - Creating a new log entry 164 | # - Performing an out-of-band entry update (i.e., gw_id provided, UUID is None) 165 | entry = Entry.from_dict(dict(msg)) 166 | 167 | # Tell static analyzers that `entry` is no longer None 168 | assert isinstance(entry, Entry) 169 | 170 | # If the entry does not specify an operator, ensure the config operator is provided instead 171 | if entry.operator == "": 172 | entry.operator = config.operator 173 | 174 | # If gw_client isn't initialized, return early and let the 'finally' clause save the log locally 175 | if gw_client is None: 176 | return (entry, f"[+] Logged to JSON file with UUID: {msg.uuid}") 177 | 178 | if entry.gw_id is None: 179 | # Save the entry so we can update it when the command completes 180 | # Note: If we don't save the entry here, it won't be saved at all if an exception occurs 181 | # This can result in duplicate JSON objects being created for the same log 182 | # Luckily, since we're saving a reference to an object, the gw_id of the saved entry will be 183 | # updated as well, if the creation is successful 184 | log_entries[msg.uuid] = entry 185 | entry.gw_id = await gw_client.create_log(entry) 186 | 187 | if entry.gw_id: 188 | saved = True 189 | return (entry, f"[+] Logged to GhostWriter with ID: {entry.gw_id}") 190 | elif await gw_client.update_log(entry) is not None: 191 | saved = True 192 | return (entry, f"[+] Updated GhostWriter log: {entry.gw_id}") 193 | 194 | raise Exception("Unknown error") 195 | 196 | except TimeoutError: 197 | error_msg = f"A timeout occurred while connecting to {config.gw_url}" 198 | logger.exception(error_msg) 199 | raise HTTPException(status_code=status.HTTP_504_GATEWAY_TIMEOUT, detail=error_msg) 200 | except TransportQueryError as e: 201 | logger.exception(f"Error encountered while fetching GraphQL schema: {e}") 202 | error_msg = e.errors[0].get("message") 203 | raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=error_msg) 204 | except GraphQLError as e: 205 | error_msg = f"Error with GraphQL query: {e}" 206 | logger.exception(error_msg) 207 | raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=error_msg) 208 | except Exception as e: 209 | error_msg = str(e) 210 | logger.exception(error_msg) 211 | raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=error_msg) 212 | finally: 213 | if entry and (not saved or config.termsync_save_all_local): 214 | await save_log(msg.uuid, entry) 215 | 216 | # If the command doesn't trigger logging, return HTTP code 204 217 | raise HTTPException(status_code=status.HTTP_204_NO_CONTENT) 218 | 219 | 220 | @app.post("/commands/") 221 | async def pre_exec(msg: Message) -> str: 222 | """Create a new log entry; intended to be used by a pre-exec hook 223 | 224 | Args: 225 | msg (Message): A Message object containing information about the command executed / action taken 226 | 227 | Returns: 228 | str: The message to display to the user 229 | """ 230 | logger.debug(f"POST /commands/: {msg}") 231 | 232 | entry: Entry 233 | response: str 234 | 235 | entry, response = await log_command(msg) 236 | 237 | return response 238 | 239 | 240 | # Endpoint to update an existing command 241 | @app.put("/commands/") 242 | async def post_exec(msg: Message) -> str: 243 | """Endpoint to update an existing log entry 244 | 245 | Intended to be used by a post-exec hook. 246 | This will create a new log entry if not existing match is found. It's better to have a duplicate than no log at all. 247 | 248 | Args: 249 | msg (Message): A Message object containing information about the command executed / action taken 250 | 251 | Returns: 252 | str: The message to display to the user 253 | """ 254 | global log_entries 255 | 256 | logger.debug(f"PUT /commands/: {msg}") 257 | 258 | # The command field from a bash session will include the start timestamp; split it from the command 259 | # Example msg.command: '2023-04-11 19:18:24 ps' 260 | if m := match(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (.*)", msg.command): 261 | (_, msg.command) = m.groups() 262 | 263 | entry: Entry 264 | response: str 265 | 266 | # Create or update the log entry 267 | entry, response = await log_command(msg) 268 | 269 | # Remove the entry from the buffer so the buffer doesn't get huge 270 | # Note: The removal is done here, rather than in log_command() in case no previous entry existed and the creation 271 | # flow was followed 272 | if log_entries.get(msg.uuid): 273 | del log_entries[msg.uuid] 274 | 275 | return response 276 | 277 | 278 | @app.on_event("shutdown") 279 | async def app_shutdown() -> None: 280 | """Export a GhostWriter CSV file on server shutdown""" 281 | try: 282 | csv_filepath: Path = export_csv(Path(config.termsync_json_log_dir), Path(config.termsync_json_log_dir)) 283 | logger.info(f"Exported cached logs to: {csv_filepath}") 284 | except Exception as e: 285 | logger.exception(e) 286 | 287 | 288 | def run(host: str = config.termsync_listen_host, port: int = config.termsync_listen_port): 289 | """Run the API server using uvicorn 290 | 291 | Args: 292 | host (str, optional): The host address where the server will bind. Defaults to config.termsync_listen_host. 293 | port (int, optional): The port where the server will bind. Defaults to config.termsync_listen_port. 294 | """ 295 | # Note: Imported here rather than at the top because it is optional 296 | import uvicorn # isort:skip 297 | 298 | uvicorn.run(app, host=host, port=port) 299 | 300 | 301 | if __name__ == "__main__": 302 | run() 303 | -------------------------------------------------------------------------------- /src/terminal_sync/config.py: -------------------------------------------------------------------------------- 1 | """Defines a Config object used to store application settings""" 2 | 3 | # Standard Libraries 4 | import logging 5 | import os 6 | from dataclasses import asdict 7 | from dataclasses import dataclass 8 | from dataclasses import field 9 | from pathlib import Path 10 | from typing import Any 11 | from typing import Generator 12 | 13 | # Third-party Libraries 14 | from yaml import safe_load 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | @dataclass 20 | class Config: 21 | """Defines a Config object used to store application settings 22 | 23 | Default settings defined in this class will be overridden by values in the config file, and both will be overridden 24 | by any matching environment variables (i.e., upper-case setting name). 25 | 26 | Attributes: 27 | gw_api_key_graphql (str): A GhostWriter GraphQL API key 28 | gw_api_key_rest (str): A GhostWriter REST API key 29 | gw_description_token (str): String used to delimit the command and an optional description; defaults to `#desc` 30 | gw_oplog_id (int): The ID number of the GhostWriter Oplog where entries will be recorded 31 | gw_url (str): The URL for your GhostWriter instance 32 | operator (str): The name / identifier of the user creating the log entries 33 | termsync_config (Path): The path to the config file; defaults to `config.yaml` 34 | termsync_json_log_dir (str): The directory where JSON log files are written; defaults to `log_archive` 35 | termsync_keywords (list[str]): List of keywords that will trigger logging a command to GhostWriter 36 | termsync_listen_host (str): The host address where the server will bind 37 | termsync_listen_port (int): The host port where the server will bind 38 | termsync_save_all_local (bool): Whether to save all logs using the JSON file (may have a performance impact); 39 | defaults to False 40 | termsync_timeout_seconds (int): The number of seconds the server will wait for a response from GhostWriter 41 | """ 42 | 43 | gw_api_key_graphql: str = "" 44 | gw_api_key_rest: str = "" 45 | gw_description_token: str = "#desc" 46 | gw_oplog_id: int = 0 47 | gw_url: str = "" 48 | operator: str | None = None 49 | termsync_config: Path = Path("config.yaml") 50 | termsync_json_log_dir: str = "log_archive" 51 | termsync_listen_host: str = "127.0.0.1" 52 | termsync_listen_port: int = 8000 53 | termsync_save_all_local: bool = False 54 | termsync_timeout_seconds: int = 3 55 | 56 | # TODO: Automatically add keywords "exported" by registered command parsers 57 | # TODO: This list should only contain keywords that don't have an associated command parser 58 | termsync_keywords: list[str] = field(default_factory=list) 59 | 60 | def __post_init__(self) -> None: 61 | """Override default settings with values from the config file or environment variables""" 62 | setting_name: str 63 | value: Any 64 | new_value: Any 65 | 66 | # Load environment variables from .env file 67 | try: 68 | # Note: Imported here rather than at the top because it is optional 69 | from dotenv import load_dotenv # isort:skip 70 | 71 | load_dotenv() 72 | except ImportError: 73 | logger.warning('dotenv is not installed; skipping loading ".env"') 74 | 75 | # Override the default config filepath using an environment variable, if it exists 76 | config_filepath: Path = Path(os.getenv("TERMSYNC_CONFIG") or self.termsync_config) 77 | 78 | # Load settings from config file, if it exists 79 | if config_filepath.exists(): 80 | logger.info(f"Logging config from: {config_filepath}") 81 | 82 | with open(config_filepath) as in_file: 83 | for setting_name, value in (safe_load(in_file) or {}).items(): 84 | if hasattr(self, setting_name): 85 | setattr(self, setting_name, value) 86 | else: 87 | raise Exception(f"{setting_name} is not a supported setting") 88 | else: 89 | logger.warning(f"Unable to load config from file; {config_filepath} does not exist") 90 | 91 | # Override settings with any matching environment variables 92 | for setting_name, value in self: 93 | if new_value := os.getenv(setting_name.upper()): 94 | # If an environment variable setting exists, parse the value as YAML in order to handle 95 | # lists, dictionaries, ints, booleans, etc. 96 | setattr(self, setting_name, safe_load(new_value)) 97 | 98 | if not self.gw_url or (not self.gw_api_key_graphql and not self.gw_api_key_rest): 99 | # Cannot log to GhostWriter without a URL or API key; enable local log storage as a backup 100 | self.termsync_save_all_local = True 101 | logger.warning("No GhostWriter API key specified; activity will not be logged to GhostWriter!") 102 | logger.info("Local logging enabled as a fallback") 103 | 104 | if self.gw_oplog_id < 0: 105 | raise ValueError("Oplog ID must be a positive integer") 106 | 107 | if not self.gw_description_token.startswith("#"): 108 | raise ValueError("gw_description_token must start with a '#'") 109 | 110 | if self.gw_description_token not in self.termsync_keywords: 111 | self.termsync_keywords.append(self.gw_description_token) 112 | 113 | def __iter__(self) -> Generator: 114 | """Iterate through the object's attributes 115 | 116 | Yields: 117 | A tuple containing an attribute name and its value 118 | """ 119 | yield from asdict(self).items() 120 | -------------------------------------------------------------------------------- /src/terminal_sync/export_csv.py: -------------------------------------------------------------------------------- 1 | """Converts a terminal_sync JSON log archive to a GhostWriter-compatible CSV file. 2 | 3 | It can be run as a standalone utility or called as a library, and was specifically designed with no external 4 | dependencies so it can be run on any system, without terminal_sync needing to be installed. 5 | """ 6 | # Standard Libraries 7 | from argparse import ArgumentParser 8 | from csv import QUOTE_MINIMAL 9 | from csv import DictWriter 10 | from datetime import datetime 11 | from json import load 12 | from pathlib import Path 13 | 14 | 15 | def export_csv(log_dir: Path, export_dir: Path = Path(".")) -> Path: 16 | """Generate a GhostWriter-compatible CSV file from all the JSON files in the specified log directory 17 | 18 | Args: 19 | log_dir (Path): The directory containing JSON logs 20 | export_dir (Path, optional): The directory where the CSV export will be written. Defaults to Path("."). 21 | 22 | Returns: 23 | str: The name of the exported CSV file 24 | """ 25 | # Construct the CSV file output path with export timestamp 26 | csv_filepath: Path = Path(export_dir) / f"termsync_export_{datetime.utcnow().strftime('%F_%H%M%S')}.csv" 27 | json_filepath: Path 28 | 29 | csv_columns: list[str] = [ 30 | "oplog_id", 31 | "start_date", 32 | "end_date", 33 | "source_ip", 34 | "dest_ip", 35 | "tool", 36 | "user_context", 37 | "command", 38 | "description", 39 | "output", 40 | "comments", 41 | "operator_name", 42 | ] 43 | 44 | # Open the CSV file and create a DictWriter 45 | with open(csv_filepath, "w", newline="") as csv_file: 46 | writer: DictWriter = DictWriter(csv_file, fieldnames=csv_columns, quoting=QUOTE_MINIMAL) 47 | 48 | writer.writeheader() 49 | 50 | # Iterate through each JSON file in the log_dir 51 | for json_filepath in log_dir.glob("*.json"): 52 | # Read the contents of the JSON file and add it as a row to the CSV file 53 | with open(json_filepath) as json_file: 54 | writer.writerow(load(json_file)) 55 | 56 | return csv_filepath 57 | 58 | 59 | if __name__ == "__main__": 60 | parser = ArgumentParser() 61 | parser.add_argument( 62 | "-l", 63 | "--log-dir", 64 | dest="log_dir", 65 | type=Path, 66 | required=True, 67 | help="The path to a directory containing terminal_sync JSON logs", 68 | ) 69 | parser.add_argument( 70 | "-o", 71 | "--output-dir", 72 | dest="output_dir", 73 | default=".", 74 | type=Path, 75 | help="The directory where the CSV export will be written", 76 | ) 77 | args = parser.parse_args() 78 | 79 | try: 80 | csv_filepath: Path = export_csv(args.log_dir, args.output_dir) 81 | print(f"[+] Successfully exported logs to: {csv_filepath}") 82 | except Exception as e: 83 | print(f"[-] Error: {e}") 84 | -------------------------------------------------------------------------------- /src/terminal_sync/ghostwriter.py: -------------------------------------------------------------------------------- 1 | """Defines a GhostWriter client class""" 2 | 3 | # Standard Libraries 4 | import logging 5 | from collections.abc import Callable 6 | 7 | # Third-party Libraries 8 | import aiohttp 9 | from gql import Client 10 | from gql import gql 11 | from gql.client import DocumentNode 12 | from gql.transport.aiohttp import AIOHTTPTransport 13 | 14 | # Internal Libraries 15 | from terminal_sync import __version__ as termsync_version 16 | from terminal_sync.log_entry import Entry 17 | 18 | logger = logging.getLogger("terminal_sync") 19 | 20 | # Suppress overly verbose logging 21 | logging.getLogger("gql.transport.aiohttp").setLevel(logging.WARNING) 22 | 23 | 24 | class GhostWriterClient: 25 | """Defines a GhostWriter client 26 | 27 | Attributes: 28 | base_url (str): The base URL where GhostWriter is hosted (e.g., "https://ghostwriter.example.com") 29 | oplog_id (int): The ID of the GhostWriter Oplog where entries will be written 30 | headers (dict[str, str]): A dictionary of HTTP headers used to communicate with GhostWriter 31 | rest_url (str): The base URL for REST API communications 32 | """ 33 | 34 | # Query inserting a new log entry 35 | _insert_query: DocumentNode = gql( 36 | """ 37 | mutation InsertTerminalSyncLog ( 38 | $oplog_id: bigint!, $start_date: timestamptz, $end_date: timestamptz, $source_ip: String, 39 | $dest_ip: String, $tool: String, $user_context: String, $command: String, $description: String, 40 | $output: String, $comments: String, $operator_name: String 41 | ) { 42 | insert_oplogEntry(objects: { 43 | oplog: $oplog_id, 44 | startDate: $start_date, 45 | endDate: $end_date, 46 | sourceIp: $source_ip, 47 | destIp: $dest_ip, 48 | tool: $tool, 49 | userContext: $user_context, 50 | command: $command, 51 | description: $description, 52 | output: $output, 53 | comments: $comments, 54 | operatorName: $operator_name, 55 | }) { 56 | returning { id } 57 | } 58 | } 59 | """ 60 | ) 61 | 62 | # Query for updating an existing log entry 63 | _update_query: DocumentNode = gql( 64 | """ 65 | mutation UpdateTerminalSyncLog ( 66 | $id: bigint!, $oplog_id: bigint!, $start_date: timestamptz, $end_date: timestamptz, $source_ip: String, 67 | $dest_ip: String, $tool: String, $user_context: String, $command: String, $description: String, 68 | $output: String, $comments: String, $operator_name: String 69 | ) { 70 | update_oplogEntry(where: { 71 | id: {_eq: $id} 72 | }, _set: { 73 | oplog: $oplog_id, 74 | startDate: $start_date, 75 | endDate: $end_date, 76 | sourceIp: $source_ip, 77 | destIp: $dest_ip, 78 | tool: $tool, 79 | userContext: $user_context, 80 | command: $command, 81 | description: $description, 82 | output: $output, 83 | comments: $comments, 84 | operatorName: $operator_name, 85 | }) { 86 | returning { id } 87 | } 88 | } 89 | """ 90 | ) 91 | 92 | def __init__(self, url: str, graphql_api_key: str = "", rest_api_key: str = "", timeout_seconds: int = 10) -> None: 93 | """Initializes a GhostWriter client 94 | 95 | Args: 96 | url (str): The base URL where GhostWriter is hosted (e.g., "https://ghostwriter.example.com") 97 | graphql_api_key (str, optional): A GhostWriter GraphQL API key. Defaults to "". 98 | rest_api_key (str, optional): A GhostWriter REST API key. Defaults to "". 99 | timeout_seconds (int, optional): Seconds the client will wait for a response. Defaults to 10. 100 | 101 | Raises: 102 | ValueError: If an invald neither API key was specified 103 | """ 104 | # Validate arguments 105 | if not url.startswith("http"): 106 | raise ValueError("Invalid GhostWriter URL") 107 | 108 | if not graphql_api_key and not rest_api_key: 109 | raise ValueError("No GhostWriter API key specified") 110 | 111 | self.base_url: str = url.rstrip("/") 112 | 113 | self.headers: dict[str, str] = { 114 | "User-Agent": f"terminal_sync/{termsync_version}", 115 | "Authorization": f"Bearer {graphql_api_key}" if graphql_api_key else f"Api-Key {rest_api_key}", 116 | "Content-Type": "application/json", 117 | } 118 | 119 | # Set create_log() and update_log() functions to call the GraphQL implementation 120 | self.create_log: Callable = self._create_entry_graphql 121 | self.update_log: Callable = self._update_entry_graphql 122 | 123 | if graphql_api_key: 124 | logger.info("Using the GraphQL API") 125 | url = f"{self.base_url}/v1/graphql" 126 | # WORKAROUND: When running Docker on a Windows host, the application will always hang waiting for the SSL 127 | # connection to terminate. The ssl_close_timeout is therefore set to 0 to avoid a negative user experience 128 | self._transport: AIOHTTPTransport = AIOHTTPTransport( 129 | url=url, headers=self.headers, ssl_close_timeout=0, timeout=timeout_seconds 130 | ) 131 | else: 132 | logger.info("Using the REST API") 133 | # Important: If you leave off the trailing "/" on oplog/api/entries/ then this POST will return "200 OK" 134 | # without actually doing anything 135 | self.rest_url: str = f"{self.base_url}/oplog/api/entries/" 136 | 137 | # Redirect create_log() and update_log() function calls to the REST implementation 138 | self.create_log = self._create_entry_rest 139 | self.update_log = self._update_entry_rest 140 | 141 | # ========================================================================= 142 | # ****** Helper Functions ***** 143 | # ========================================================================= 144 | 145 | async def log(self, entry: Entry) -> int | None: 146 | """Convenience function that calls either create or update depending on whether entry.gw_id is populated 147 | 148 | Args: 149 | entry (Entry): The entry object to be recorded 150 | 151 | Returns: 152 | int | None: The ID of the GhostWriter entry if successful, otherwise None 153 | """ 154 | if entry.gw_id is None: 155 | return await self._create_log(entry) 156 | 157 | return await self._update_log(entry) 158 | 159 | # ========================================================================= 160 | # ****** REST function ***** 161 | # ========================================================================= 162 | 163 | async def _create_entry_rest(self, entry: Entry) -> int | None: 164 | """Create an entry in Ghostwriter's Oplog (POST) using the REST API 165 | 166 | Args: 167 | entry (Entry): The entry object to be recorded 168 | 169 | Returns: 170 | int | None: The ID of the GhostWriter log entry 171 | 172 | Raises: 173 | Exception: If an error occurred while communicating with GhostWriter 174 | """ 175 | logger.debug(f"[REST] Creating entry for: {entry}") 176 | 177 | data: dict[str, int | str] = entry.gw_fields() 178 | 179 | async with aiohttp.ClientSession(headers=self.headers) as session: 180 | async with session.post(self.rest_url, json=data) as resp: 181 | resp = await resp.json() 182 | logger.debug(f"Response: {resp}") 183 | 184 | if resp.get("detail"): 185 | raise Exception(resp.get("detail")) 186 | 187 | logger.info(f'Logged "{entry.command}" to GhostWriter as ID: {resp.get("id")}') 188 | return resp.get("id") 189 | 190 | async def _update_entry_rest(self, entry: Entry) -> int | None: 191 | """Update an entry in Ghostwriter's Oplog (PUT) using the REST API 192 | 193 | Args: 194 | entry (Entry): The entry object to be recorded 195 | 196 | Returns: 197 | int | None: The ID of the GhostWriter log entry 198 | 199 | Raises: 200 | Exception: If an error occurred while communicating with GhostWriter 201 | """ 202 | logger.debug(f"[REST] Updating entry: {entry}") 203 | 204 | url: str = f"{self.rest_url}{entry.gw_id}/?format=json" 205 | 206 | data: dict[str, int | str] = entry.gw_fields() 207 | 208 | async with aiohttp.ClientSession(headers=self.headers) as session: 209 | async with session.put(url, json=data) as resp: 210 | resp = await resp.json() 211 | logger.debug(f"Response: {resp}") 212 | 213 | if resp.get("detail"): 214 | raise Exception(resp.get("detail")) 215 | 216 | logger.info(f"Updated GhostWriter entry with ID: {entry.gw_id}") 217 | return resp.get("id") 218 | 219 | # ========================================================================= 220 | # ****** GraphQL functions ***** 221 | # ========================================================================= 222 | 223 | async def _execute_query(self, query: DocumentNode, values: dict) -> dict: 224 | """Execute a GraphQL query against the Ghostwriter server 225 | 226 | Args: 227 | query (DocumentNode): The GraphQL query to execute 228 | values (dict): The parameters to pass to the query 229 | 230 | Returns: 231 | A dictionary containing the server's response 232 | 233 | Raises: 234 | Exception: If an error occurred while communicating with GhostWriter 235 | """ 236 | logger.debug(f"variable_values: {values}") 237 | 238 | async with Client(transport=self._transport, fetch_schema_from_transport=True) as session: 239 | return await session.execute(query, variable_values=values) 240 | 241 | async def _create_entry_graphql(self, entry: Entry) -> int | None: 242 | """Create an entry in Ghostwriter's Oplog using the GraphQL API 243 | 244 | Args: 245 | entry (Entry): The entry object to be recorded 246 | 247 | Returns: 248 | int | None: The ID of the GhostWriter log entry 249 | 250 | Raises: 251 | Exception: If an error occurred while communicating with GhostWriter 252 | """ 253 | logger.debug(f"[GraphQL] Creating entry for: {entry}") 254 | 255 | resp: dict = await self._execute_query(self._insert_query, entry.gw_fields()) 256 | logger.debug(f"Response: {resp}") 257 | # Example response: `{'insert_oplogEntry': {'returning': [{'id': 192}]}}` 258 | 259 | entry_id: int = resp.get("insert_oplogEntry", {}).get("returning", [{"id": None}])[0].get("id") 260 | 261 | if entry_id: 262 | logger.info(f"Logged to GhostWriter with ID: {entry_id}") 263 | return entry_id 264 | else: 265 | logger.error(f"Did not receive a response with data from Ghostwriter's GraphQL API! Response: {resp}") 266 | 267 | return None 268 | 269 | async def _update_entry_graphql(self, entry: Entry) -> int | None: 270 | """Update an entry in Ghostwriter's Oplog using the GraphQL API 271 | 272 | Args: 273 | entry (Entry): The entry object to be recorded 274 | 275 | Returns: 276 | int | None: The ID of the GhostWriter log entry 277 | 278 | Raises: 279 | Exception: If an error occurred while communicating with GhostWriter 280 | """ 281 | logger.debug(f"[GraphQL] Updating log entry: {entry}") 282 | 283 | resp: dict = await self._execute_query(self._update_query, {"id": entry.gw_id, **entry.gw_fields()}) 284 | logger.debug(f"Response: {resp}") 285 | # Example response: `{'update_oplogEntry': {'returning': [{'id': 192}]}}` 286 | 287 | entry_id: int = resp.get("update_oplogEntry", {}).get("returning", [{"id": None}])[0].get("id") 288 | 289 | if entry_id: 290 | logger.info(f"Updated GhostWriter entry with ID: {entry_id}") 291 | return entry_id 292 | else: 293 | logger.error(f"Did not receive a response with data from Ghostwriter's GraphQL API! Response: {resp}") 294 | 295 | return None 296 | -------------------------------------------------------------------------------- /src/terminal_sync/log_entry.py: -------------------------------------------------------------------------------- 1 | """Defines a GhostWriter log entry class""" 2 | 3 | # Standard Libraries 4 | from dataclasses import asdict 5 | from dataclasses import dataclass 6 | from datetime import datetime 7 | from socket import AF_INET 8 | from socket import SOCK_DGRAM 9 | from socket import gethostname 10 | from socket import socket 11 | from typing import Any 12 | from typing import Generator 13 | 14 | 15 | @dataclass 16 | class Entry: 17 | """Defines a GhostWriter log entry 18 | 19 | Attributes: 20 | oplog_id (int): The ID of the GhostWriter Oplog where entries will be written 21 | command (str): The text of the command executed 22 | start_time (datetime): Timestamp when the command/activity began 23 | end_time (datetime): Timestamp when the command/activity completed 24 | gw_id (int | None): The log entry ID returned by GhostWriter 25 | Used to update the entry on completion 26 | source_host (str | None): The host where the activity originated 27 | operator (str | None): The name/identifier of the person creating the entry 28 | destination_host (str | None): The target host of the activity 29 | tool (str | None): The name/identifier of the tool used 30 | user_context (str | None): Identifier for the credentials used for the command/activity 31 | output (str): The output or results of the command/activity 32 | Given the limited space in the GhostWriter UI, this is usually a success or failure note 33 | description (str): The goal/intent/reason for running the command or performing the action 34 | comments (str): Misc additional information about the command / activity 35 | """ 36 | 37 | command: str 38 | comments: str = "Logged by terminal_sync" 39 | description: str = "" 40 | destination_host: str | None = None 41 | start_time: datetime = datetime.utcnow() # start_time must be initialized before end_time 42 | end_time: datetime = datetime.utcnow() 43 | gw_id: int | None = None 44 | operator: str | None = None 45 | oplog_id: int = 0 46 | output: str = "" 47 | source_host: str | None = None 48 | tool: str | None = None 49 | user_context: str | None = None 50 | uuid: str = "" 51 | # TODO: Tags are not supported by the current GraphQL interface 52 | # tags (list[str] | None): An arbitrary list of tags 53 | # tags: list[str] = field(default_factory=list) 54 | 55 | def __post_init__(self) -> None: 56 | """Initialize source_host to the local host if not explicitly set""" 57 | self.source_host = self.source_host or self._get_local_host() 58 | 59 | def __iter__(self) -> Generator: 60 | """Iterate through an entry's attributes 61 | 62 | Yields: 63 | A tuple containing an attribute name and its value 64 | """ 65 | yield from asdict(self).items() 66 | 67 | def _get_local_host(self) -> str: 68 | """Return the hostname and IP address of the local host 69 | 70 | Returns: 71 | str: The hostname and IP address of the local host (e.g., "WORKSTATION (192.168.1.20)") 72 | """ 73 | local_ip: str = "127.0.0.1" 74 | 75 | try: 76 | # connect() for UDP doesn't send packets but can be used to determine the primary NIC 77 | s: socket = socket(AF_INET, SOCK_DGRAM) 78 | s.connect(("8.8.8.8", 0)) 79 | local_ip = s.getsockname()[0] 80 | except Exception: 81 | pass 82 | 83 | return f"{gethostname()} ({local_ip})" 84 | 85 | @property # type: ignore[no-redef] 86 | def command(self) -> str: 87 | """Return the command 88 | 89 | Returns: 90 | str: The command 91 | """ 92 | return self._command 93 | 94 | @command.setter 95 | def command(self, command: str) -> None: 96 | """Set the command, stripping whitespace from the beginning and end 97 | 98 | Args: 99 | command (str): The new command value 100 | """ 101 | # Note: Omitting this isinstance() check caused the code to generate: 102 | # "AttributeError: 'property' object has no attribute 'strip'" 103 | # if the command was not explicitly set when initializing an object 104 | # (even when a default value was provided) 105 | self._command = command.strip() if isinstance(command, str) else "" 106 | 107 | @property # type: ignore[no-redef] 108 | def description(self) -> str: 109 | """Return the description 110 | 111 | Returns: 112 | str: The entry description 113 | """ 114 | return self._description 115 | 116 | @description.setter 117 | def description(self, description: str) -> None: 118 | """Set the description, stripping whitespace from the beginning and end 119 | 120 | Args: 121 | description (str): The new description 122 | """ 123 | self._description = description.strip() if isinstance(description, str) else "" 124 | 125 | @property # type: ignore[no-redef] 126 | def start_time(self) -> str: 127 | """Return the start_time as a string in "YYYY-mm-dd HH:MM:SS" format 128 | 129 | Returns: 130 | str: The start_time in "YYYY-mm-dd HH:MM:SS" format 131 | """ 132 | return self._start_time.strftime("%F %H:%M:%S") 133 | 134 | @start_time.setter 135 | def start_time(self, start_time: datetime) -> None: 136 | """Set the start_time 137 | 138 | Args: 139 | start_time (datetime): The new start_time 140 | """ 141 | self._start_time = start_time if isinstance(start_time, datetime) else datetime.utcnow() 142 | 143 | @property # type: ignore[no-redef] 144 | def end_time(self) -> str: 145 | """Return the end_time as a string in "YYYY-mm-dd HH:MM:SS" format 146 | 147 | Returns: 148 | str: The end_time in "YYYY-mm-dd HH:MM:SS" format 149 | """ 150 | return self._end_time.strftime("%F %H:%M:%S") 151 | 152 | @end_time.setter 153 | def end_time(self, end_time: datetime) -> None: 154 | """Set the end_time, making sure it's equal to or greater than the start_time 155 | 156 | Args: 157 | end_time (datetime): The new end_time 158 | """ 159 | # Ensure end_date is a datetime object 160 | end_time = end_time if isinstance(end_time, datetime) else datetime.utcnow() 161 | 162 | # Note: Use _start_time rather than start_time to avoid: 163 | # TypeError: '<' not supported between instances of 'datetime.datetime' and 'str' 164 | if end_time < self._start_time: 165 | self._end_time = self._start_time 166 | else: 167 | self._end_time = end_time 168 | 169 | @classmethod 170 | def from_dict(cls, args: dict[str, Any]): 171 | """Return a new Entry object populated from the provided dictionary 172 | 173 | This method filters out all key-value pairs that are not Entry attributes and uses the valid ones 174 | to create a new Entry object 175 | 176 | Args: 177 | args (dict[str, Any]): A dictionary containing Entry attributes and associated values 178 | 179 | Returns: 180 | Entry: The new Entry object 181 | """ 182 | # Note: Used __dataclass_fields__ rather than hasattr() because hasattr() returns false unless the field 183 | # has a default value 184 | return cls(**{key: value for key, value in args.items() if key in cls.__dataclass_fields__}) 185 | 186 | def gw_fields(self) -> dict[str, int | str]: 187 | """Return a dictionary of non-empty entry attributes using the Ghostwriter field names 188 | 189 | Returns: 190 | A dictionary of fields for the GhostWriter REST API 191 | """ 192 | # Map attribute names to REST API key names 193 | field_map: dict[str, str] = { 194 | "destination_host": "dest_ip", 195 | "end_time": "end_date", 196 | "operator": "operator_name", 197 | "source_host": "source_ip", 198 | "start_time": "start_date", 199 | } 200 | 201 | omitted_fields: list[str] = ["gw_id", "uuid"] 202 | 203 | # Construct a dictionary containing all non-empty entry attributes 204 | # Substitute the entry attribute name with the REST-specific field name 205 | return { 206 | field_map.get(attr, attr): value for attr, value in self if value is not None and attr not in omitted_fields 207 | } 208 | 209 | def json_filename(self) -> str: 210 | """Return a JSON filename for this entry with format: __.json 211 | 212 | This format ensures logs will first be grouped by oplog then listed chronologically 213 | 214 | Returns: 215 | str: The JSON filename for this entry 216 | """ 217 | return f"{self.oplog_id}_{self._start_time.strftime('%F_%H%M%S')}_{self.uuid}.json" 218 | 219 | def fields(self) -> dict[str, int | str]: 220 | """Return a dictionary of the entry's non-empty attributes 221 | 222 | Returns: 223 | dict[str, int | str]: The entry's non-empty attributes 224 | """ 225 | return {attr: value for attr, value in self if value is not None} 226 | 227 | def update(self, args: dict[str, Any]) -> None: 228 | """Update specified entry attributes 229 | 230 | Args: 231 | args (dict[str, Any]): A dictionary mapping attributes names to their new values 232 | """ 233 | protected_fields: list[str] = ["oplog_id", "start_time", "uuid"] 234 | 235 | for attr, value in args.items(): 236 | # Prevent accidentally overwriting values or adding attributes that shouldn't exist 237 | if value is not None and attr in self.__dataclass_fields__ and attr not in protected_fields: 238 | # if value is not None and self.hasattr(self, key) and key not in protected_fields: 239 | setattr(self, attr, value) 240 | -------------------------------------------------------------------------------- /terminal_sync.psm1: -------------------------------------------------------------------------------- 1 | # ============================================================================= 2 | # ****** Configuration Settings ****** 3 | # ============================================================================= 4 | 5 | # The name / identifier of the user creating the log entries 6 | $env:OPERATOR = "" 7 | 8 | # The IP and port where the terminal_sync server is running 9 | $global:TermSyncServer = "127.0.0.1:8000" 10 | 11 | # Enable / disable terminal_sync logging at runtime 12 | $global:TermSyncLogging = $true 13 | 14 | # Controls the verbosity of the terminal_sync console output 15 | # 0 (None): No terminal_sync output will be displayed 16 | # 1 (ExecOnly): Only the executed command and timestamps will be displayed 17 | # 2 (SuccessOnly): terminal_sync will display a message on logging success 18 | # 3 (IgnoreTermSyncConnError): Only errors contacting the terminal_sync server will be suppressed 19 | # 4 (All): All terminal_sync output will be displayed 20 | $global:TermSyncVerbosity = 4 21 | 22 | # The number of seconds the client will wait for a response from the terminal_sync server 23 | $global:TimeoutSec = 4 24 | 25 | 26 | # ============================================================================= 27 | # ****** Management Functions ****** 28 | # ============================================================================= 29 | 30 | function Enable-TermSync { 31 | $global:TermSyncLogging = $true 32 | Write-Host "[+] terminal_sync logging enabled" 33 | } 34 | 35 | function Disable-TermSync { 36 | $global:TermSyncLogging = $False 37 | Write-Host "[+] terminal_sync logging disabled" 38 | } 39 | 40 | function Set-TermSyncVerbosity { 41 | # Use the DisplayLevel enum as the parameter type to allow tab completion 42 | param( 43 | [Parameter(Mandatory)] 44 | [ValidateNotNullOrEmpty()] 45 | [DisplayLevel]$Level 46 | ) 47 | $global:TermSyncVerbosity = $Level 48 | 49 | Write-Host "[+] terminal_sync log level set to: $Level" 50 | } 51 | 52 | # ============================================================================= 53 | # ****** Terminal Sync Client ****** 54 | # ============================================================================= 55 | 56 | # Define the console verbosity levels 57 | Add-Type -TypeDefinition @" 58 | public enum DisplayLevel 59 | { 60 | None = 0, 61 | ExecOnly = 1, 62 | SuccessOnly = 2, 63 | IgnoreTermSyncConnError = 3, 64 | All = 4 65 | } 66 | "@ 67 | 68 | # Enumerated type to track the log status of each command 69 | Add-Type -TypeDefinition @" 70 | public enum LogStatus 71 | { 72 | Logged, 73 | Completed 74 | } 75 | "@ 76 | 77 | # Dictionary used to track which commands have be logged and successfully updated 78 | $global:CommandTracker = @{} 79 | 80 | # Initialize the command index so our command count aligns with the Id attribute in PowerShell's history 81 | # Add 1 because the command to load this module (e.g., `Import-Module terminal_sync.psm1`) will increment the history 82 | $global:CommandIndex = $(Get-History -Count 1).Id + 1 83 | 84 | # Pre-exec hook 85 | function PSConsoleHostReadLine { 86 | # Prompt the user for a command line to submit, save it in a variable and 87 | # pass it through, by enclosing it in (...) 88 | $Command = [Microsoft.PowerShell.PSConsoleReadLine]::ReadLine($Host.Runspace, $ExecutionContext) 89 | 90 | if ($TermSyncLogging) { 91 | $StartTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss") 92 | 93 | try { 94 | # Only react to non-blank lines 95 | if ($command.Trim()) { 96 | # Increment command index so it will match `$(Get-History -Count 1).Id` for this command 97 | $global:CommandIndex += 1 98 | 99 | if ($TermSyncVerbosity -gt [DisplayLevel]::None) { 100 | Write-Host "[*] Executed: `"$Command`" at $StartTime" 101 | } 102 | 103 | $Params = @{ 104 | Method = "Post" 105 | Uri = "http://$TermSyncServer/commands/" 106 | ContentType = "application/json" 107 | TimeoutSec = $TimeoutSec 108 | Body = (@{ 109 | uuid = "$($Host.InstanceId).$global:CommandIndex" 110 | command = $Command 111 | start_time = $StartTime 112 | source_host = $env:SRC_HOST 113 | comments = "PowerShell Session: $($Host.InstanceId)" 114 | operator = $env:OPERATOR 115 | } | ConvertTo-Json 116 | ) 117 | } 118 | 119 | try { 120 | $Response = Invoke-RestMethod @Params 121 | 122 | # If the request is successful, the response will be a string to be displayed to the user 123 | # If the command does not trigger logging, an HTTP 204 with no body is returned; don't print anything 124 | if ($Response) { 125 | if ($TermSyncVerbosity -gt [DisplayLevel]::ExecOnly) { 126 | Write-Host $Response 127 | } 128 | 129 | # Store the status of the command 130 | $global:CommandTracker.Set_Item($global:CommandIndex.ToString(), [LogStatus]::Logged) 131 | } 132 | } 133 | catch { 134 | # Get the HTTP status code 135 | $StatusCode = $_.Exception.Response.StatusCode.value__ 136 | 137 | # An error occurred; the server will return a JSON object with a "detail" attribute 138 | # (e.g., '{"detail":"An error occurred while trying to log to GhostWriter: Cannot connect to host"}') 139 | if ($StatusCode) { 140 | # If an exception occurred server-side; throw an exception with the message from the server 141 | throw $($_ | ConvertFrom-Json).detail 142 | } 143 | elseif ($_.ToString() -eq "Unable to connect to the remote server") { 144 | if ($TermSyncVerbosity -gt [DisplayLevel]::IgnoreTermSyncConnError) { 145 | # Clarify which server could not be contacted 146 | throw "Unable to connect to terminal_sync server" 147 | } 148 | } 149 | else { 150 | # Otherwise, re-raise the exception 151 | throw $_ 152 | } 153 | } 154 | } 155 | } 156 | catch { 157 | if ($TermSyncVerbosity -gt [DisplayLevel]::SuccessOnly) { 158 | # Clearly indicate the error is from terminal_sync and not the command the user ran 159 | Write-Host -ForegroundColor Red "[terminal_sync] [ERROR]: $_" 160 | } 161 | } 162 | } 163 | 164 | # IMPORTANT: Ensure the original command is returned so it gets executed 165 | $command 166 | } 167 | 168 | # Post-exec hook 169 | function Prompt { 170 | if ($TermSyncLogging) { 171 | try { 172 | # Retrieve the last command 173 | $LastCommand = Get-History -Count 1 174 | 175 | # If the last command exists and isn't complete, process it 176 | if ($LastCommand -and $global:CommandTracker[$LastCommand.Id.ToString()] -ne [LogStatus]::Completed) { 177 | 178 | # Convert the start and end timestamps to properly formatted strings (in UTC) 179 | $StartTime = $LastCommand.StartExecutionTime.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss") 180 | $EndTime = $LastCommand.EndExecutionTime.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss") 181 | 182 | if ($TermSyncVerbosity -gt [DisplayLevel]::None) { 183 | Write-Host "[+] Completed: `"$($LastCommand.CommandLine)`" at $EndTime" 184 | } 185 | 186 | $Params = @{ 187 | Method = "Put" 188 | Uri = "http://$TermSyncServer/commands/" 189 | ContentType = "application/json" 190 | TimeoutSec = $TimeoutSec 191 | Body = (@{ 192 | # Use the PowerShell session ID and the index of the command to uniquely identify it 193 | uuid = "$($Host.InstanceId).$($LastCommand.Id)" 194 | command = $LastCommand.CommandLine 195 | start_time = $StartTime 196 | end_time = $EndTime 197 | source_host = $env:SRC_HOST 198 | # Set output to the execution status of the command 199 | output = if ($?) { "Success" } else { "Failed" } 200 | comments = "PowerShell Session: $($Host.InstanceId)" 201 | operator = $env:OPERATOR 202 | } | ConvertTo-Json 203 | ) 204 | } 205 | 206 | try { 207 | $Response = Invoke-RestMethod @Params 208 | 209 | # If the request is successful, the response will be a string to be displayed to the user 210 | # If the command does not trigger logging, an HTTP 204 with no body is returned; don't print anything 211 | if ($Response) { 212 | if ($TermSyncVerbosity -gt [DisplayLevel]::ExecOnly) { 213 | Write-Host $Response 214 | } 215 | 216 | # Mark the command as completed so we don't get a duplicate if the user presses Enter on an empty line 217 | $global:CommandTracker.Set_Item($LastCommand.Id.ToString(), [LogStatus]::Completed) 218 | } 219 | } 220 | catch { 221 | # Get the HTTP status code 222 | $StatusCode = $_.Exception.Response.StatusCode.value__ 223 | 224 | # An error occurred; the server will return a JSON object with a "detail" attribute 225 | # (e.g., '{"detail":"An error occurred while trying to log to GhostWriter: Cannot connect to host"}') 226 | if ($StatusCode) { 227 | # If an exception occurred server-side; throw an exception with the message from the server 228 | throw $($_ | ConvertFrom-Json).detail 229 | } 230 | elseif ($_.ToString() -eq "Unable to connect to the remote server") { 231 | if ($TermSyncVerbosity -gt [DisplayLevel]::IgnoreTermSyncConnError) { 232 | # Clarify which server could not be contacted 233 | throw "Unable to connect to terminal_sync server" 234 | } 235 | } 236 | else { 237 | # Otherwise, re-raise the exception 238 | throw $_ 239 | } 240 | } 241 | } 242 | } 243 | catch { 244 | if ($TermSyncVerbosity -gt [DisplayLevel]::SuccessOnly) { 245 | # Clearly indicate the error is from terminal_sync and not the command the user ran 246 | Write-Host -ForegroundColor Red "[terminal_sync] [ERROR]: $_" 247 | } 248 | } 249 | } 250 | 251 | # Return the PowerShell prompt 252 | "PS $($executionContext.SessionState.Path.CurrentLocation.Path)$('>' * ($nestedPromptLevel + 1)) " 253 | } 254 | -------------------------------------------------------------------------------- /terminal_sync.sh: -------------------------------------------------------------------------------- 1 | # ============================================================================= 2 | # ****** Configuration Settings ****** 3 | # ============================================================================= 4 | 5 | # The name / identifier of the user creating the log entries 6 | export OPERATOR="" 7 | 8 | # The IP and port where the terminal_sync server is running 9 | TERMSYNC_SERVER="127.0.0.1:8000" 10 | 11 | # Whether terminal_sync logging is enabled; any value greater than 0 means enabled 12 | TERMSYNC_LOGGING=1 13 | 14 | # Controls the verbosity of the terminal_sync console output 15 | # 0 (None): No terminal_sync output will be displayed 16 | # 1 (ExecOnly): Only the executed command and timestamps will be displayed 17 | # 2 (SuccessOnly): terminal_sync will display a message on logging success 18 | # 3 (IgnoreTermSyncConnError): Only errors contacting the terminal_sync server will be suppressed 19 | # 4 (All): All terminal_sync output will be displayed 20 | # 5 (Debug): Additional debugging information will be displayed 21 | TERMSYNC_VERBOSITY=4 22 | 23 | # The number of seconds the client will wait for a response from the terminal_sync server 24 | TERMSYNC_TIMEOUT=4 25 | 26 | 27 | # ============================================================================= 28 | # ****** Installation and Setup ****** 29 | # ============================================================================= 30 | 31 | # NOTE: These installation steps are run automatically every time the script is invoked to make sure the necessary 32 | # dependencies are in place and haven't been removed since the last execution 33 | 34 | BASH_PREEXEC_PATH=~/bash-preexec.sh 35 | 36 | # If bash-preexec.sh does not exist, warn the user about running scripts from the Internet, 37 | # if they accept the risk, download it 38 | if [[ ! -f $BASH_PREEXEC_PATH ]]; then 39 | echo -e "\e[31m[!] Security Warning\e[0m: This script will download and run bash-preexec.sh (https://raw.githubusercontent.com/rcaloras/bash-preexec/master/bash-preexec.sh). Downloading and running scripts from the Internet can be dangerous; you are advised to review the contents of this script before continuing." 40 | 41 | read -p "[?] I accept the risk [y|N]: " -N 1 42 | echo '' # Start a new line after the previous 'read' command 43 | 44 | # Bail unless the user specifically agrees 45 | if [[ ! $REPLY =~ ^[Yy]$ ]]; then 46 | echo -e "\e[31m[X] Operation cancelled\e[0m" 47 | # IMPORTANT: Use 'return' rather than 'exit' because this script will be invoked via 'source' and 48 | # 'exit' would kill the shell 49 | return 1 50 | fi 51 | 52 | echo -e "\e[1;34m[*] Downloading bash-preexec.sh...\e[0m" 53 | 54 | # Download bash-preexec.sh 55 | # This is used to hook commands before they execute 56 | curl https://raw.githubusercontent.com/rcaloras/bash-preexec/master/bash-preexec.sh > $BASH_PREEXEC_PATH 57 | 58 | if [[ ! -f $BASH_PREEXEC_PATH ]]; then 59 | echo -e "\e[31m[-] Error: Failed to download bash-preexec.sh\e[0m" 60 | return 1 61 | fi 62 | 63 | # Ensure bash-preexec.sh is executable 64 | chmod +x $BASH_PREEXEC_PATH 65 | 66 | echo -e "\e[1;32m[+] Successfully downloaded bash-preexec.sh\e[0m" 67 | 68 | # If bash-preexec doesn't exist, assume this is the first run, prompt the user whether they want to install terminal_sync 69 | echo "[*] This looks like your first time running terminal_sync on this host." 70 | read -p "[?] Would you like to permanently install the bash hooks? [Y|n]: " -N 1 71 | echo '' # Start a new line after the previous 'read' command 72 | 73 | # Default to installing unless the user says no 74 | if [[ ! $REPLY =~ ^[Nn]$ ]]; then 75 | echo "source '$(realpath $PWD/$BASH_SOURCE)'" >> ~/.bashrc 76 | echo -e "\e[1;32m[+] Successfully added terminal_sync.sh to ~/.bashrc\e[0m" 77 | fi 78 | fi 79 | 80 | # Install required packages (only if one doesn't exist, so we don't do this every time terminal_sync runs) 81 | # Source: https://unix.stackexchange.com/questions/46081/identifying-the-system-package-manager 82 | packages_needed='curl jq' 83 | 84 | for package in $packages_needed; do 85 | if [[ ! -x $(command -v $package) ]]; then 86 | echo -e "\e[1;34m[*] ${package} not installed; attempting to install...\e[0m" 87 | 88 | if [ -x "$(command -v apk)" ]; then sudo apk add -y --no-cache $packages_needed 89 | elif [ -x "$(command -v apt-get)" ]; then sudo apt-get install -y $packages_needed 90 | elif [ -x "$(command -v dnf)" ]; then sudo dnf install -y $packages_needed 91 | elif [ -x "$(command -v zypper)" ]; then sudo zypper install -y $packages_needed 92 | else 93 | echo -e "\e[31m[-] Error: Package manager not found. You must manually install: ${packages_needed}\e[0m" >&2 94 | return 1 95 | fi 96 | fi 97 | done 98 | 99 | 100 | # ============================================================================= 101 | # ****** Management Functions ****** 102 | # ============================================================================= 103 | 104 | DISPLAY_LEVELS=(NONE EXEC_ONLY SUCCESS_ONLY IGNORE_TERMSYNC_CONN_ERROR ALL DEBUG) 105 | 106 | num_display_levels=${#DISPLAY_LEVELS[@]} 107 | 108 | # Declare variables for each display level so they can be referenced in the code 109 | for ((i=0; i < $num_display_levels; i++)); do 110 | name="DISPLAY_${DISPLAY_LEVELS[i]}" 111 | declare ${name}=$i 112 | done 113 | 114 | function Enable-TermSync { 115 | TERMSYNC_LOGGING=1 116 | echo "[+] terminal_sync logging enabled" 117 | } 118 | 119 | function Disable-TermSync { 120 | TERMSYNC_LOGGING=0 121 | echo "[+] terminal_sync logging disabled" 122 | } 123 | 124 | function Set-TermSyncVersbosity() { 125 | echo "Display Levels:" 126 | echo "---------------" 127 | 128 | for ((i=0; i < $num_display_levels; i++)); do 129 | echo "${i} = ${DISPLAY_LEVELS[i]}" 130 | done 131 | 132 | # Add an extra new line for visual separation 133 | echo "" 134 | echo "[*] Current log level: ${DISPLAY_LEVELS[TERMSYNC_VERBOSITY]}" 135 | 136 | while [ 1 ]; do 137 | read -p "[?] Enter the number of your desired display level: " -N 1 138 | 139 | # Verify the input is within the valid range 140 | if [[ $REPLY -ge 0 && $REPLY -lt $num_display_levels ]]; then 141 | TERMSYNC_VERBOSITY=$REPLY 142 | break 143 | fi 144 | 145 | echo "[-] '${REPLY}' is not a valid log level" 146 | done 147 | 148 | echo "" # Print a newline, since read only accepts a single character 149 | echo "[+] terminal_sync log level set to: ${DISPLAY_LEVELS[TERMSYNC_VERBOSITY]}" 150 | } 151 | 152 | 153 | # ============================================================================= 154 | # ****** Terminal Sync Client ****** 155 | # ============================================================================= 156 | 157 | # Load bash-preexec to enable `preexec` and `precmd` hooks 158 | source $BASH_PREEXEC_PATH 159 | 160 | # Set the history time format to timestamp each command run (format: 'YYYY-mm-dd HH:MM:SS') 161 | # This is useful as a fallback and is expected by the `sed` command that parses the command line from the history 162 | export HISTTIMEFORMAT="%F %T " 163 | 164 | # Set the comment to: " session: " 165 | COMMENT="$(ps -p $$ -o comm | tail -n 1) session: $(cat /proc/sys/kernel/random/uuid)" 166 | 167 | 168 | function display_response() { 169 | response=$* 170 | 171 | # If an error occured the server will return a JSON object with a "detail" attribute 172 | # (e.g., '{"detail":"An error occurred while trying to log to GhostWriter: Cannot connect to host"}') 173 | # Use `jq` to parse it and display the error message; otherwise print the message from the server 174 | if [[ $response == *"{\"detail\":"* ]]; then 175 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_SUCCESS_ONLY ]]; then 176 | error_msg="$(echo $response | jq -r '.detail')" 177 | echo -e "\e[31m[terminal_sync] [ERROR]: ${error_msg}\e[0m" 178 | fi 179 | elif [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_EXEC_ONLY && ${#response} -gt 0 ]]; then 180 | # Print the response, stripping leading and trailing quotes 181 | echo $response | sed -e 's/^"//' -e 's/"$//' 182 | fi 183 | } 184 | 185 | function create_log() { 186 | command=$1 187 | 188 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_NONE ]]; then 189 | echo "[*] Executed: \"${command}\" at ${CMD_START_TIME}" 190 | fi 191 | 192 | json_data="$(jq --null-input \ 193 | --arg uuid "${CMD_UUID}" \ 194 | --arg command "${command}" \ 195 | --arg start_time "${CMD_START_TIME}" \ 196 | --arg source_host "${SRC_HOST}" \ 197 | --arg comments "${COMMENT}" \ 198 | --arg operator "${OPERATOR}" \ 199 | '{"uuid": $uuid, "command": $command, "start_time": $start_time, 200 | "source_host": $source_host, "comments": $comments, "operator": $operator}'\ 201 | )" 202 | 203 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 204 | echo $json_data | jq 205 | fi 206 | 207 | # Set whether curl should display connection error messages 208 | [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_IGNORE_TERMSYNC_CONN_ERROR ]] && show_error='-S' || show_error='' 209 | 210 | response=$(curl -s ${show_error} -X 'POST' "http://${TERMSYNC_SERVER}/commands/" -H 'accept: application/json' \ 211 | -H 'Content-Type: application/json' --connect-timeout ${TERMSYNC_TIMEOUT} -d "${json_data}") 212 | 213 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_EXEC_ONLY ]]; then 214 | display_response $response 215 | fi 216 | } 217 | 218 | function update_log() { 219 | command=$1 220 | error_code=$2 221 | 222 | end_time=$(date -u +'%F %H:%M:%S') 223 | 224 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_NONE ]]; then 225 | echo -e "\n[+] Completed: \"${command}\" at ${end_time}" 226 | fi 227 | 228 | # Determine whether the command succeeded; if the command failed return the error code as well 229 | [[ $error_code -eq 0 ]] && output='Success' || output="Failed; Return Code: ${error_code}" 230 | 231 | json_data="$(jq --null-input \ 232 | --arg uuid "${CMD_UUID}" \ 233 | --arg command "${command}" \ 234 | --arg start_time "${CMD_START_TIME}" \ 235 | --arg end_time "${end_time}" \ 236 | --arg source_host "${SRC_HOST}" \ 237 | --arg output "${output}" \ 238 | --arg comments "${COMMENT}" \ 239 | --arg operator "${OPERATOR}" \ 240 | '{"uuid": $uuid, "command": $command, "start_time": $start_time, "end_time": $end_time, 241 | "source_host": $source_host, "output": $output, "comments": $comments, "operator": $operator}'\ 242 | )" 243 | 244 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 245 | echo $json_data | jq 246 | fi 247 | 248 | # Set whether curl should display connection error messages 249 | [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_IGNORE_TERMSYNC_CONN_ERROR ]] && show_error='-S' || show_error='' 250 | 251 | response=$(curl -s ${show_error} -X 'PUT' "http://${TERMSYNC_SERVER}/commands/" -H 'accept: application/json' \ 252 | -H 'Content-Type: application/json' --connect-timeout ${TERMSYNC_TIMEOUT} -d "${json_data}") 253 | 254 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_EXEC_ONLY ]]; then 255 | display_response $response 256 | fi 257 | } 258 | 259 | # Defines a pre-execution hook to log the command to GhostWriter 260 | function preexec() { 261 | command="$*" 262 | 263 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 264 | echo "Command: $command" 265 | fi 266 | 267 | # If terminal_sync is enabled and the command isn't empty (i.e., length of `command` > 0), try to log the command 268 | if [[ $TERMSYNC_LOGGING -gt 0 && ${#command} -gt 0 ]]; then 269 | # Generate a UUID for the command; save it and the start time as environment variables so they can be accessed 270 | # by the post-exec hook 271 | CMD_UUID="$(cat /proc/sys/kernel/random/uuid)" 272 | CMD_START_TIME="$(date -u +'%F %H:%M:%S')" 273 | 274 | create_log "${command}" 275 | fi 276 | } 277 | 278 | # Defines a post-execution hook that updates the command entry in GhostWriter 279 | function precmd() { 280 | # IMPORTANT: This must be the first command or else we'll get the status of a command we run 281 | error_code="$?" 282 | 283 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 284 | echo "Command UUID: $CMD_UUID" 285 | echo "Command Start Time: $CMD_START_TIME" 286 | echo "Error Code: $error_code" 287 | fi 288 | 289 | # If logging is enabled and CMD_UUID was set by the pre-exec hook, try to update the entry 290 | # The CMD_UUID check prevents duplicate submissions when the user submits a blank line 291 | if [[ $TERMSYNC_LOGGING -gt 0 && ${#CMD_UUID} -gt 0 ]]; then 292 | # Get the last command and strip the index and timestamp from the front 293 | last_command=$(export LC_ALL=C; builtin history 1 | sed '1 s/^[^:]*[^ ]* *//'); 294 | # last_command="$(export LC_ALL=C; builtin history 1)" 295 | # start_time="$(echo $last_command | awk '{print $2,$3}')" 296 | 297 | update_log "${last_command}" "${error_code}" 298 | 299 | # Unset variables to prevent logging unless another command is run (i.e., ignore blank lines) 300 | unset CMD_UUID 301 | unset CMD_START_TIME 302 | fi 303 | } 304 | 305 | 306 | echo -e "\e[1;32m[+] Successfully loaded terminal_sync hooks\e[0m" 307 | -------------------------------------------------------------------------------- /terminal_sync_zsh.sh: -------------------------------------------------------------------------------- 1 | # ============================================================================= 2 | # ****** Configuration Settings ****** 3 | # ============================================================================= 4 | 5 | # The name / identifier of the user creating the log entries. Defaults to the config.yaml operator if no operator is specified. 6 | export OPERATOR="" 7 | 8 | # The IP and port where the terminal_sync server is running 9 | TERMSYNC_SERVER="127.0.0.1:8000" 10 | 11 | # Whether terminal_sync logging is enabled; any value greater than 0 means enabled 12 | TERMSYNC_LOGGING=1 13 | 14 | # Controls the verbosity of the terminal_sync console output 15 | # 0 (None): No terminal_sync output will be displayed 16 | # 1 (ExecOnly): Only the executed command and timestamps will be displayed 17 | # 2 (SuccessOnly): terminal_sync will display a message on logging success 18 | # 3 (IgnoreTermSyncConnError): Only errors contacting the terminal_sync server will be suppressed 19 | # 4 (All): All terminal_sync output will be displayed 20 | # 5 (Debug): Additional debugging information will be displayed 21 | TERMSYNC_VERBOSITY=4 22 | 23 | # The number of seconds the client will wait for a response from the terminal_sync server 24 | TERMSYNC_TIMEOUT=4 25 | 26 | 27 | # ============================================================================= 28 | # ****** Installation and Setup ****** 29 | # ============================================================================= 30 | 31 | # If the script doesn't exist in ~/.zshrc, it adds itself to the file. 32 | if ! grep -q "${0:a}" ~/.zshrc; then 33 | echo "source ${0:a}" >> ~/.zshrc 34 | echo "\e[1;32m[+] Successfully added terminal_sync.sh to ~/.zshrc\e[0m" 35 | fi 36 | 37 | # Install required packages (only if one doesn't exist, so we don't do this every time terminal_sync runs) 38 | # Source: https://unix.stackexchange.com/questions/46081/identifying-the-system-package-manager 39 | packages_needed=(curl jq) 40 | 41 | for package in $packages_needed; do 42 | if [[ ! -x $(command -v $package) ]]; then 43 | echo "\e[1;34m[*] ${package} not installed; attempting to install...\e[0m" 44 | 45 | if [ -x "$(command -v apk)" ]; then sudo apk add -y --no-cache $packages_needed 46 | elif [ -x "$(command -v apt-get)" ]; then sudo apt-get install -y $packages_needed 47 | elif [ -x "$(command -v dnf)" ]; then sudo dnf install -y $packages_needed 48 | elif [ -x "$(command -v zypper)" ]; then sudo zypper install -y $packages_needed 49 | else 50 | echo "\e[31m[-] Error: Package manager not found. You must manually install: ${packages_needed}\e[0m" >&2 51 | return 1 52 | fi 53 | fi 54 | done 55 | 56 | 57 | # ============================================================================= 58 | # ****** Management Functions ****** 59 | # ============================================================================= 60 | 61 | DISPLAY_LEVELS=(NONE EXEC_ONLY SUCCESS_ONLY IGNORE_TERMSYNC_CONN_ERROR ALL DEBUG) 62 | 63 | num_display_levels=${#DISPLAY_LEVELS[@]} 64 | 65 | # Declare variables for each display level so they can be referenced in the code 66 | for ((i=0; i < $num_display_levels; i++)); do 67 | name="DISPLAY_${DISPLAY_LEVELS[i]}" 68 | declare ${name}=$i 69 | done 70 | 71 | Enable-TermSync() { 72 | TERMSYNC_LOGGING=1 73 | echo "[+] terminal_sync logging enabled" 74 | } 75 | 76 | Disable-TermSync() { 77 | TERMSYNC_LOGGING=0 78 | echo "[+] terminal_sync logging disabled" 79 | } 80 | 81 | Set-TermSyncVersbosity() { 82 | echo "Display Levels:" 83 | echo "---------------" 84 | 85 | for ((i=0; i < $num_display_levels; i++)); do 86 | echo "${i} = ${DISPLAY_LEVELS[i]}" 87 | done 88 | 89 | # Add an extra new line for visual separation 90 | echo "" 91 | echo "[*] Current log level: ${DISPLAY_LEVELS[TERMSYNC_VERBOSITY]}" 92 | 93 | while [ 1 ]; do 94 | echo "[?] Enter the number of your desired display level: " 95 | read -k 96 | 97 | # Verify the input is within the valid range 98 | if [[ $REPLY -ge 0 && $REPLY -lt $num_display_levels ]]; then 99 | TERMSYNC_VERBOSITY=$REPLY 100 | break 101 | fi 102 | 103 | echo "[-] '${REPLY}' is not a valid log level" 104 | done 105 | 106 | echo "" # Print a newline, since read only accepts a single character 107 | echo "[+] terminal_sync log level set to: ${DISPLAY_LEVELS[TERMSYNC_VERBOSITY]}" 108 | } 109 | 110 | 111 | # ============================================================================= 112 | # ****** Terminal Sync Client ****** 113 | # ============================================================================= 114 | 115 | # Set the history time format to timestamp each command run (format: 'YYYY-mm-dd HH:MM:SS') 116 | # This is useful as a fallback and is expected by the `sed` command that parses the command line from the history 117 | # TODO: review this: 118 | export HISTTIMEFORMAT="%F %T " 119 | 120 | # Set the comment to: " session: " 121 | COMMENT="$(ps -p $$ -o comm | tail -n 1) session: $(cat /proc/sys/kernel/random/uuid)" 122 | 123 | display_response() { 124 | response=$* 125 | 126 | # If an error occured the server will return a JSON object with a "detail" attribute 127 | # (e.g., '{"detail":"An error occurred while trying to log to GhostWriter: Cannot connect to host"}') 128 | # Use `jq` to parse it and display the error message; otherwise print the message from the server 129 | if [[ $response == *"{\"detail\":"* ]]; then 130 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_SUCCESS_ONLY ]]; then 131 | error_msg="$(echo $response | jq -r '.detail')" 132 | echo "\e[31m[terminal_sync] [ERROR]: ${error_msg}\e[0m" 133 | fi 134 | elif [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_EXEC_ONLY && ${#response} -gt 0 ]]; then 135 | # Print the response, stripping leading and trailing quotes 136 | echo $response | sed -e 's/^"//' -e 's/"$//' 137 | fi 138 | } 139 | 140 | create_log() { 141 | command=$1 142 | 143 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_NONE ]]; then 144 | echo "[*] Executed: \"${command}\" at ${CMD_START_TIME}" 145 | fi 146 | 147 | json_data="$(jq --null-input \ 148 | --arg uuid "${CMD_UUID}" \ 149 | --arg command "${command}" \ 150 | --arg start_time "${CMD_START_TIME}" \ 151 | --arg source_host "${SRC_HOST}" \ 152 | --arg comments "${COMMENT}" \ 153 | --arg operator "${OPERATOR}" \ 154 | '{"uuid": $uuid, "command": $command, "start_time": $start_time, 155 | "source_host": $source_host, "comments": $comments, "operator": $operator}'\ 156 | )" 157 | 158 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 159 | echo $json_data | jq 160 | fi 161 | 162 | # Set whether curl should display connection error messages 163 | [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_IGNORE_TERMSYNC_CONN_ERROR ]] && show_error='-S' || show_error='' 164 | 165 | response=$(curl -s ${show_error} -X 'POST' "http://${TERMSYNC_SERVER}/commands/" -H 'accept: application/json' \ 166 | -H 'Content-Type: application/json' --connect-timeout ${TERMSYNC_TIMEOUT} -d "${json_data}") 167 | 168 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_EXEC_ONLY ]]; then 169 | display_response $response 170 | fi 171 | } 172 | 173 | update_log() { 174 | command=$1 175 | error_code=$2 176 | 177 | end_time=$(date -u +'%F %H:%M:%S') 178 | 179 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_NONE ]]; then 180 | echo "\n[+] Completed: \"${command}\" at ${end_time}" 181 | fi 182 | 183 | # Determine whether the command succeeded; if the command failed return the error code as well 184 | [[ $error_code -eq 0 ]] && output='Success' || output="Failed; Return Code: ${error_code}" 185 | 186 | json_data="$(jq --null-input \ 187 | --arg uuid "${CMD_UUID}" \ 188 | --arg command "${command}" \ 189 | --arg start_time "${CMD_START_TIME}" \ 190 | --arg end_time "${end_time}" \ 191 | --arg source_host "${SRC_HOST}" \ 192 | --arg output "${output}" \ 193 | --arg comments "${COMMENT}" \ 194 | --arg operator "${OPERATOR}" \ 195 | '{"uuid": $uuid, "command": $command, "start_time": $start_time, "end_time": $end_time, 196 | "source_host": $source_host, "output": $output, "comments": $comments, "operator": $operator}'\ 197 | )" 198 | 199 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 200 | echo $json_data | jq 201 | fi 202 | 203 | # Set whether curl should display connection error messages 204 | [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_IGNORE_TERMSYNC_CONN_ERROR ]] && show_error='-S' || show_error='' 205 | 206 | response=$(curl -s ${show_error} -X 'PUT' "http://${TERMSYNC_SERVER}/commands/" -H 'accept: application/json' \ 207 | -H 'Content-Type: application/json' --connect-timeout ${TERMSYNC_TIMEOUT} -d "${json_data}") 208 | 209 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_EXEC_ONLY ]]; then 210 | display_response $response 211 | fi 212 | } 213 | 214 | # Defines a pre-execution hook to log the command to GhostWriter 215 | preexec() { 216 | command=$1 217 | 218 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 219 | echo "Command: $command" 220 | fi 221 | 222 | # If terminal_sync is enabled and the command isn't empty (i.e., length of `command` > 0), try to log the command 223 | if [[ $TERMSYNC_LOGGING -gt 0 && ${#command} -gt 0 ]]; then 224 | # Generate a UUID for the command; save it and the start time as environment variables so they can be accessed 225 | # by the post-exec hook 226 | CMD_UUID="$(cat /proc/sys/kernel/random/uuid)" 227 | CMD_START_TIME="$(date -u +'%F %H:%M:%S')" 228 | 229 | create_log "${command}" 230 | fi 231 | } 232 | 233 | # Defines a post-execution hook that updates the command entry in GhostWriter 234 | precmd() { 235 | # IMPORTANT: This must be the first command or else we'll get the status of a command we run 236 | error_code="$?" 237 | 238 | if [[ $TERMSYNC_VERBOSITY -gt $DISPLAY_ALL ]]; then 239 | echo "Command UUID: $CMD_UUID" 240 | echo "Command Start Time: $CMD_START_TIME" 241 | echo "Error Code: $error_code" 242 | fi 243 | 244 | # If logging is enabled and CMD_UUID was set by the pre-exec hook, try to update the entry 245 | # The CMD_UUID check prevents duplicate submissions when the user submits a blank line 246 | if [[ $TERMSYNC_LOGGING -gt 0 && ${#CMD_UUID} -gt 0 ]]; then 247 | # Get the last command and strip the index and timestamp from the front 248 | 249 | # last_command=$(export LC_ALL=C; builtin history 1 | sed '1 s/^[^:]*[^ ]* *//'); 250 | # last_command="$(export LC_ALL=C; builtin history 1)" 251 | # start_time="$(echo $last_command | awk '{print $2,$3}')" 252 | 253 | update_log "${command}" "${error_code}" 254 | 255 | # Unset variables to prevent logging unless another command is run (i.e., ignore blank lines) 256 | unset CMD_UUID 257 | unset CMD_START_TIME 258 | fi 259 | } 260 | 261 | echo "\e[1;32m[+] Successfully loaded terminal_sync hooks\e[0m" -------------------------------------------------------------------------------- /tests/test_log_entry.py: -------------------------------------------------------------------------------- 1 | # Standard Libraries 2 | from datetime import datetime 3 | from re import Pattern 4 | from re import compile 5 | from typing import Any 6 | from typing import Generator 7 | 8 | # Third-party Libraries 9 | from pytest import fixture 10 | from pytest import raises 11 | 12 | # Internal Libraries 13 | from terminal_sync.log_entry import Entry 14 | 15 | # Define common patterns that can be reused in multiple tests 16 | DATE_PATTERN: Pattern = compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}") 17 | HOST_PATTERN: Pattern = compile(r".*? \(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\)") 18 | 19 | 20 | @fixture 21 | def basic_entry() -> Entry: 22 | """Return a new Entry object using only mandatory arguments 23 | 24 | Returns: 25 | Entry: An Entry object with only mandatory fields set 26 | """ 27 | return Entry(command=" proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL ") 28 | 29 | 30 | @fixture 31 | def filled_out_entry() -> Entry: 32 | """Return a new Entry object using all arguments 33 | 34 | Returns: 35 | Entry: An Entry object with all fields set 36 | """ 37 | return Entry( 38 | command=" proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL ", 39 | comments="PowerShell Session: bd58093b-9b74-4f49-b71f-7f6dcf4be130", 40 | description="Uploaded files to target", 41 | destination_host="", 42 | end_time=datetime.fromisoformat("2022-12-01 09:29:10"), # 50 seconds less than the start time 43 | gw_id=2, 44 | oplog_id=1, 45 | operator="neo", 46 | output="Success", 47 | source_host="localhost (127.0.0.1)", 48 | start_time=datetime.fromisoformat("2022-12-01 09:30:00"), 49 | tool="smbclient.py", 50 | user_context="SGC.HWS.MIL/sam.carter", 51 | uuid="c8f897a6-d3c9-4432-8d29-4df99773892d.18", 52 | # tags=None, 53 | ) 54 | 55 | 56 | def test_creation(filled_out_entry: Entry) -> None: 57 | """Verify all fields are set properly when creating an entry 58 | 59 | Args: 60 | filled_out_entry (Entry): An Entry object with all fields set 61 | """ 62 | entry: Entry = filled_out_entry 63 | 64 | assert ( 65 | entry.command == "proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL" 66 | ), f"Expected whitespace to be stripped from the command; got '{entry.command}'" 67 | assert entry.comments == "PowerShell Session: bd58093b-9b74-4f49-b71f-7f6dcf4be130" 68 | assert entry.description == "Uploaded files to target" 69 | assert entry.destination_host == "" 70 | assert entry.end_time == "2022-12-01 09:30:00", f"Expected end_time to match start_time; got: {entry.end_time}" 71 | assert entry.gw_id == 2 72 | assert entry.operator == "neo" 73 | assert entry.oplog_id == 1 74 | assert entry.output == "Success" 75 | assert entry.start_time == "2022-12-01 09:30:00" 76 | assert entry.source_host == "localhost (127.0.0.1)" 77 | assert entry.tool == "smbclient.py" 78 | assert entry.user_context == "SGC.HWS.MIL/sam.carter" 79 | assert entry.uuid == "c8f897a6-d3c9-4432-8d29-4df99773892d.18" 80 | # assert entry.tags is None 81 | 82 | 83 | def test_default_values(basic_entry: Entry) -> None: 84 | """Verify default values are set 85 | 86 | Args: 87 | basic_entry (Entry): An Entry object with only mandatory fields set 88 | """ 89 | entry: Entry = basic_entry 90 | 91 | assert ( 92 | entry.command == "proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL" 93 | ), f"Expected whitespace to be stripped from the command; got '{entry.command}'" 94 | assert entry.comments == "Logged by terminal_sync" 95 | assert entry.description == "" 96 | assert entry.destination_host is None 97 | assert isinstance(entry.end_time, str) and DATE_PATTERN.match(entry.end_time) 98 | assert entry.gw_id is None 99 | assert entry.operator is None 100 | assert entry.oplog_id == 0 101 | assert entry.output == "" 102 | assert isinstance(entry.source_host, str) and HOST_PATTERN.match( 103 | entry.source_host 104 | ), f"Expected source_host to be a string with pattern ' ()'; got {type(entry.source_host)}" 105 | assert isinstance(entry.start_time, str) and DATE_PATTERN.match(entry.start_time) 106 | assert entry.tool is None 107 | assert entry.user_context is None 108 | assert entry.uuid == "" 109 | # assert entry.tags is None 110 | 111 | 112 | def test_fields(filled_out_entry: Entry) -> None: 113 | """Verify `.fields()` returns the correct values 114 | 115 | Args: 116 | filled_out_entry (Entry): An Entry object with all fields set 117 | """ 118 | fields: dict[str, int | str] = filled_out_entry.fields() 119 | 120 | assert len(fields) == 14, f"Expected 14; got {fields}" 121 | assert fields["command"] == "proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL" 122 | assert fields["comments"] == "PowerShell Session: bd58093b-9b74-4f49-b71f-7f6dcf4be130" 123 | assert fields["description"] == "Uploaded files to target" 124 | assert fields["destination_host"] == "" 125 | assert fields["end_time"] == "2022-12-01 09:30:00" 126 | assert fields["gw_id"] == 2 127 | assert fields["operator"] == "neo" 128 | assert fields["oplog_id"] == 1 129 | assert fields["output"] == "Success" 130 | assert fields["source_host"] == "localhost (127.0.0.1)" 131 | assert fields["start_time"] == "2022-12-01 09:30:00" 132 | assert fields["tool"] == "smbclient.py" 133 | assert fields["user_context"] == "SGC.HWS.MIL/sam.carter" 134 | assert fields["uuid"] == "c8f897a6-d3c9-4432-8d29-4df99773892d.18" 135 | # assert "tags" not in fields 136 | 137 | 138 | def test_gw_fields(filled_out_entry: Entry) -> None: 139 | """Verify `.gw_fields()` returns the correct keys and values 140 | 141 | Args: 142 | filled_out_entry (Entry): An Entry object with all fields set 143 | """ 144 | fields: dict[str, int | str] = filled_out_entry.gw_fields() 145 | 146 | assert len(fields) == 12, f"Expected 12; got {fields}" 147 | assert fields["command"] == "proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL" 148 | assert fields["comments"] == "PowerShell Session: bd58093b-9b74-4f49-b71f-7f6dcf4be130" 149 | assert fields["description"] == "Uploaded files to target" 150 | assert fields["dest_ip"] == "" 151 | assert fields["end_date"] == "2022-12-01 09:30:00" 152 | assert fields["operator_name"] == "neo" 153 | assert fields["oplog_id"] == 1 154 | assert fields["output"] == "Success" 155 | assert fields["source_ip"] == "localhost (127.0.0.1)" 156 | assert fields["start_date"] == "2022-12-01 09:30:00" 157 | assert fields["tool"] == "smbclient.py" 158 | assert fields["user_context"] == "SGC.HWS.MIL/sam.carter" 159 | 160 | 161 | def test_iter(filled_out_entry) -> None: 162 | """Verify the `__iter__()` function successfully loops through all attributes and returns the correct values 163 | 164 | Args: 165 | filled_out_entry (_type_): An Entry object with all fields set 166 | """ 167 | attrs: dict[str, int | str] = { 168 | "command": "proxychains4 python3 smbclient.py SGC.HWS.MIL/sam.carter:password@SGCDC001.SGC.HWS.MIL", 169 | "comments": "PowerShell Session: bd58093b-9b74-4f49-b71f-7f6dcf4be130", 170 | "description": "Uploaded files to target", 171 | "destination_host": "", 172 | "start_time": "2022-12-01 09:30:00", 173 | "end_time": "2022-12-01 09:30:00", 174 | "gw_id": 2, 175 | "operator": "neo", 176 | "oplog_id": 1, 177 | "output": "Success", 178 | "source_host": "localhost (127.0.0.1)", 179 | "tool": "smbclient.py", 180 | "user_context": "SGC.HWS.MIL/sam.carter", 181 | "uuid": "c8f897a6-d3c9-4432-8d29-4df99773892d.18", 182 | # "tags": None, 183 | } 184 | entry_attr: str 185 | entry_value: Any 186 | 187 | gen: Generator = filled_out_entry.__iter__() 188 | 189 | assert isinstance(gen, Generator) 190 | 191 | # Verify the correct values are returned 192 | for attr, value in attrs.items(): 193 | entry_attr, entry_value = next(gen) 194 | assert entry_attr == attr 195 | assert entry_value == value 196 | 197 | # Verify there are no remaining attributes 198 | with raises(StopIteration): 199 | next(gen) 200 | 201 | 202 | def test_json_filename(filled_out_entry) -> None: 203 | """Verify the JSON filename is constructed properly 204 | 205 | Args: 206 | filled_out_entry (Entry): An Entry object with all fields set 207 | """ 208 | entry: Entry = filled_out_entry 209 | 210 | assert entry.json_filename() == "1_2022-12-01_093000_c8f897a6-d3c9-4432-8d29-4df99773892d.18.json" 211 | 212 | 213 | def test_update(filled_out_entry: Entry) -> None: 214 | """Verify that `update()` updates the end_time, output, and comments; does not update start_time; 215 | and ignores keys that do not match attributes 216 | 217 | Args: 218 | filled_out_entry (Entry): An Entry object with all fields set 219 | """ 220 | entry: Entry = filled_out_entry 221 | 222 | original_start_time: str = "2022-12-01 09:30:00" 223 | new_end_time: str = "2023-01-02 00:29:00" 224 | new_output: str = "Failed" 225 | new_comment: str = "PowerShell Session: 7f007022-1cb6-4e8d-b8b8-252e6e07943d" 226 | 227 | # Baseline the previous state 228 | assert entry.comments == "PowerShell Session: bd58093b-9b74-4f49-b71f-7f6dcf4be130" 229 | assert entry.end_time == "2022-12-01 09:30:00" 230 | assert entry.output == "Success" 231 | assert entry.start_time == original_start_time 232 | 233 | # 'invalid_key' should be ignored gracefully and not raise an exception 234 | entry.update( 235 | { 236 | "comments": new_comment, 237 | "end_time": datetime.fromisoformat(new_end_time), 238 | "invalid_key": "", 239 | "output": new_output, 240 | "start_time": datetime.fromisoformat("2023-01-02 00:30:00"), 241 | } 242 | ) 243 | 244 | # Verify start_time was not updated and the remaining fields were 245 | assert entry.comments == new_comment 246 | assert entry.end_time == new_end_time, f"End time should be updated; got: {entry.end_time}" 247 | assert entry.output == new_output, f"Expected '{new_output}'; got: {entry.output}" 248 | assert entry.start_time == original_start_time, f"Start time should not be updated; got: {entry.start_time}" 249 | 250 | # Verify if end_time < start_time, the end_time is set to match start_time 251 | new_end_time = "2022-11-30 00:00:00" 252 | entry.update({"end_time": datetime.fromisoformat(new_end_time)}) 253 | 254 | assert new_end_time < original_start_time 255 | assert entry.end_time == original_start_time, "End time set to before start time should be reset to start time" 256 | --------------------------------------------------------------------------------