From d81c4adfeb23a113a79d3d62e7db415d30da5ae3 Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Sat, 22 Jun 2024 01:44:19 +0300 Subject: [PATCH 1/5] The very first version --- .codebeatsettings | 11 + .codeclimate.yml | 39 +++ .docker/alpine.docker | 35 +++ .github/CODE_OF_CONDUCT.md | 42 +++ .github/CONTRIBUTING.md | 19 ++ .github/ISSUE_TEMPLATE.md | 51 ++++ .github/PULL_REQUEST_TEMPLATE.md | 24 ++ .github/dependabot.yml | 36 +++ .github/images/card.svg | 1 + .github/images/license.svg | 1 + .github/images/usage.svg | 83 ++++++ .github/workflows/ci.yml | 131 +++++++++ .github/workflows/codeql.yml | 33 +++ .github/workflows/docker-push.yml | 167 +++++++++++ .gitignore | 2 + .typos.toml | 2 + LICENSE | 201 +++++++++++++ Makefile | 114 ++++++++ README.md | 94 +++++- SECURITY.md | 36 +++ cli/cli.go | 468 ++++++++++++++++++++++++++++++ go.mod | 14 + go.sum | 14 + siocrypt.go | 28 ++ 24 files changed, 1644 insertions(+), 2 deletions(-) create mode 100644 .codebeatsettings create mode 100644 .codeclimate.yml create mode 100644 .docker/alpine.docker create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/dependabot.yml create mode 100644 .github/images/card.svg create mode 100644 .github/images/license.svg create mode 100644 .github/images/usage.svg create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/codeql.yml create mode 100644 .github/workflows/docker-push.yml create mode 100644 .gitignore create mode 100644 .typos.toml create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 SECURITY.md create mode 100644 cli/cli.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 siocrypt.go diff --git a/.codebeatsettings b/.codebeatsettings new file mode 100644 index 0000000..8e5dd08 --- /dev/null +++ b/.codebeatsettings @@ -0,0 +1,11 @@ +{ + "GOLANG": { + "ABC": [15, 25, 50, 70], + "LOC": [30, 45, 70, 100], + "BLOCK_NESTING": [4, 6, 8, 10], + "TOO_MANY_IVARS": [50, 75, 100, 150], + "TOO_MANY_FUNCTIONS": [64, 128, 256, 512], + "TOTAL_LOC": [1500, 3000, 5000, 10000], + "TOTAL_COMPLEXITY": [350, 600, 900, 1200] + } +} diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 0000000..16f4324 --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,39 @@ +version: "2" + +checks: + argument-count: + enabled: true + config: + threshold: 6 + complex-logic: + enabled: true + config: + threshold: 6 + file-lines: + enabled: true + config: + threshold: 1000 + method-complexity: + enabled: true + config: + threshold: 8 + method-count: + enabled: true + config: + threshold: 20 + method-lines: + enabled: true + config: + threshold: 100 + nested-control-flow: + enabled: true + config: + threshold: 6 + return-statements: + enabled: true + config: + threshold: 6 + similar-code: + enabled: false + identical-code: + enabled: false diff --git a/.docker/alpine.docker b/.docker/alpine.docker new file mode 100644 index 0000000..1d91a49 --- /dev/null +++ b/.docker/alpine.docker @@ -0,0 +1,35 @@ +## REGISTRY CONFIGURATION ###################################################### + +ARG REGISTRY="ghcr.io" + +## BUILDER ##################################################################### + +FROM ${REGISTRY}/essentialkaos/golang:alpine3.18 as builder + +WORKDIR /go/src/github.com/essentialkaos/siocrypt + +COPY . . + +RUN make deps && make all + +## FINAL IMAGE ################################################################# + +FROM ${REGISTRY}/essentialkaos/alpine:3.18 + +LABEL org.opencontainers.image.title="siocrypt" \ + org.opencontainers.image.description="Tool for encrypting/decrypting arbitrary data streams" \ + org.opencontainers.image.vendor="ESSENTIAL KAOS" \ + org.opencontainers.image.authors="Anton Novojilov" \ + org.opencontainers.image.licenses="Apache-2.0" \ + org.opencontainers.image.url="https://kaos.sh/siocrypt" \ + org.opencontainers.image.source="https://github.com/essentialkaos/siocrypt" + +COPY --from=builder /go/src/github.com/essentialkaos/siocrypt/siocrypt \ + /usr/bin/ + +# hadolint ignore=DL3018 +RUN apk add --no-cache ca-certificates + +ENTRYPOINT ["siocrypt"] + +################################################################################ diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..45abf3d --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,42 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of +fostering an open and welcoming community, we pledge to respect all people who +contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic + addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to +fairly and consistently applying these principles to every aspect of managing +this project. Project maintainers who do not follow or enforce the Code of +Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting a project maintainer at `conduct@essentialkaos.com`. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. Maintainers are +obligated to maintain confidentiality with regard to the reporter of an +incident. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..d7da3fb --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing Guidelines + +**IMPORTANT! Contribute your code only if you have an excellent understanding of project idea and all existing code base. Otherwise, a nicely formatted issue will be more helpful to us.** + +### Issues + +1. Provide product version where the problem was found; +2. Provide info about your environment; +3. Provide detailed info about your problem; +4. Provide steps to reproduce the problem; +5. Provide actual and expected results. + +### Code + +1. Check your code **before** creating pull request; +2. If tests are present in a project, add tests for your code; +3. Add inline documentation for your code; +4. Apply code style used throughout the project; +5. Create your pull request to `develop` branch (_pull requests to other branches are not allowed_). diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..fd0a652 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,51 @@ +_Before opening an issue, search for similar bug reports or feature requests on GitHub Issues. If yes, please add a_ 👍 _reaction to the existing issue. If no similar issue can be found, fill out either the "Bug Report" or the "Feature Request" section below. Erase the other section and everything on and above this line._ + +### Bug report + +**System info:** + +* **Verbose version info (`siocrypt -vv`):** +* **Install tools:** + +**Steps to reproduce:** + +1. [First Step] +2. [Second Step] +3. [and so on...] + +**Expected behavior:** + +[What you expected to happen] + +**Actual behavior:** + +[What actually happened] + +**Additional info:** + +[Include gist of relevant config, logs, etc.] + +Please run those if possible and link them from a [gist](http://gist.github.com). + +--- + +### Feature Request + +Opening a feature request kicks off a discussion. Requests may be closed if we're not actively planning to work on them. + +**Proposal:** + +[Description of the feature] + +**Current behavior:** + +[What currently happens] + +**Desired behavior:** + +[What you would like to happen] + +**Use case:** + +[Why is this important (helps with prioritizing requests)] + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..e7814b8 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,24 @@ +### What did you implement: + +Closes #XXXXX + +### How did you implement it: + +... + +### How can we verify it: + +... + +### TODO's: + +- [ ] Write tests +- [ ] Write documentation +- [ ] Check that there aren't other open pull requests for the same issue/feature +- [ ] Format your source code by `make fmt` +- [ ] Provide verification config / commands +- [ ] Enable "Allow edits from maintainers" for this PR +- [ ] Update the messages below + +**Is this ready for review?:** No +**Is it a breaking change?:** No diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d0ad1de --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,36 @@ +version: 2 + +updates: + - package-ecosystem: "gomod" + directory: "/" + target-branch: "develop" + schedule: + interval: "daily" + timezone: "Europe/London" + time: "03:00" + labels: + - "PR • MAINTENANCE" + assignees: + - "andyone" + reviewers: + - "andyone" + groups: + all: + applies-to: version-updates + update-types: + - "minor" + - "patch" + + - package-ecosystem: "github-actions" + directory: "/" + target-branch: "develop" + schedule: + interval: "daily" + timezone: "Europe/London" + time: "04:00" + labels: + - "PR • MAINTENANCE" + assignees: + - "andyone" + reviewers: + - "andyone" diff --git a/.github/images/card.svg b/.github/images/card.svg new file mode 100644 index 0000000..1396f34 --- /dev/null +++ b/.github/images/card.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.github/images/license.svg b/.github/images/license.svg new file mode 100644 index 0000000..8e82228 --- /dev/null +++ b/.github/images/license.svg @@ -0,0 +1 @@ +license: Apache-2.0licenseApache-2.0 diff --git a/.github/images/usage.svg b/.github/images/usage.svg new file mode 100644 index 0000000..9db8839 --- /dev/null +++ b/.github/images/usage.svg @@ -0,0 +1,83 @@ + + + + siocrypt Usage + + + + + + + + + + + + + + + + + + + Terminal + + Usage: siocrypt {options} input output + Without an input file, tool reads data from standard input and writes to standard + output if no output file is specified. + Password provided via --password/-p option will be masked in process command. Also, + password can't be specified using SIOCRYPT_PASSWORD environment variable. + Options + --decrypt, -D ............ Decrypt data + --password, -p password .. Password for encrypting/decrypting + --cipher, -c cipher ...... Cipher to use (AES256/C20P1305) + --no-color, -nc .......... Disable colors in output + --help, -h ............... Show this help message + --version, -v ............ Show version + Examples + cat data.enc | siocrypt -p TeSt1234 | grep John + Read data from standard input and grep over decrypted output + cat data.enc | siocrypt -p TeSt1234 -- data.txt + Read data from standard input and save decrypted data as data.txt + siocrypt -p TeSt1234 data.enc | grep John + Read data from file data.enc and grep over decrypted output + siocrypt -p TeSt1234 data.enc data.txt + Read data from file data.enc and save decrypted data as data.txt + SIOCRYPT_PASSWORD=TeSt1234 siocrypt data.enc data.txt + Use password from environment variable while decrypting data + + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ced11e4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,131 @@ +name: CI + +on: + push: + branches: [master, develop] + pull_request: + branches: [master] + workflow_dispatch: + inputs: + force_run: + description: 'Force workflow run' + required: true + type: choice + options: [yes, no] + +permissions: + actions: read + contents: read + statuses: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + Go: + name: Go + runs-on: ubuntu-latest + + strategy: + matrix: + go: [ '1.21.x', '1.22.x' ] + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go }} + + - name: Download dependencies + run: make deps + + - name: Run tests + run: make all + + Hadolint: + name: Hadolint + runs-on: ubuntu-latest + + needs: Go + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Check dockerfiles with Hadolint + uses: essentialkaos/hadolint-action@v1 + with: + files: .docker/*.docker + + Typos: + name: Typos + runs-on: ubuntu-latest + + needs: Go + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Check spelling + uses: crate-ci/typos@master + + DockerBuild: + name: Docker Build Check + runs-on: ubuntu-latest + + needs: Hadolint + + env: + REGISTRY: ghcr.io + + strategy: + matrix: + image: [ 'alpine' ] + + steps: + - name: Check event type + run: | + if [[ "${{github.event_name}}" != "pull_request" ]] ; then + echo "::notice::Event type is not 'pull_request', all job actions will be skipped" + fi + + # This step is a hack for needs+if issue with actions + # More info about issue: https://github.com/actions/runner/issues/491 + + - name: Checkout + uses: actions/checkout@v4 + if: ${{ github.event_name == 'pull_request' }} + + - name: Login to DockerHub + uses: docker/login-action@v3 + env: + DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + if: ${{ github.event_name == 'pull_request' && env.DOCKERHUB_USERNAME != '' }} + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + if: ${{ github.event_name == 'pull_request' }} + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build Docker image + if: ${{ github.event_name == 'pull_request' }} + run: | + docker build --build-arg REGISTRY=${REGISTRY} -f .docker/${{matrix.image}}.docker -t ${{matrix.image}} . + + - name: Show info about built Docker image + uses: essentialkaos/docker-info-action@v1 + if: ${{ github.event_name == 'pull_request' }} + with: + image: ${{matrix.image}} + show-labels: true diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..bfc4df5 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,33 @@ +name: "CodeQL" + +on: + push: + branches: [master, develop] + pull_request: + branches: [master] + schedule: + - cron: '0 3 * * */2' + +permissions: + security-events: write + actions: read + contents: read + +jobs: + analyse: + name: Analyse + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: go + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/docker-push.yml b/.github/workflows/docker-push.yml new file mode 100644 index 0000000..758de78 --- /dev/null +++ b/.github/workflows/docker-push.yml @@ -0,0 +1,167 @@ +name: "Docker Push" + +on: + release: + types: [published] + workflow_dispatch: + inputs: + force_rebuild: + description: 'Force container rebuild' + required: true + type: choice + options: [yes, no] + schedule: + - cron: '30 12 * * *' + +permissions: + packages: write + contents: read + +env: + IMAGE_NAME: ${{ github.repository }} + +jobs: + Docker: + name: Docker Build & Publish + runs-on: ubuntu-latest + + env: + DOCKER_FILE: alpine + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Login to DockerHub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Checkout the latest tag + run: | + rev=$(git rev-list --tags --max-count=1) + tag=$(git describe --tags "$rev") + + if [[ -z "$tag" ]] ; then + echo "::error::Can't find the latest tag" + exit 1 + fi + + echo -e "\033[34mRev:\033[0m $rev" + echo -e "\033[34mTag:\033[0m $tag" + + git checkout "$tag" + + - name: Prepare metadata for build + id: metadata + run: | + rev=$(git rev-list --tags --max-count=1) + version=$(git describe --tags "$rev" | tr -d 'v') + + if [[ -z "$version" ]] ; then + echo "::error::Can't find version info" + exit 1 + fi + + docker_file=".docker/${{env.DOCKER_FILE}}.docker" + base_image=$(grep 'FROM ' $docker_file | grep -v 'builder' | sed 's#${REGISTRY}/##' | tail -1 | cut -f2 -d' ') + + if [[ -z "$base_image" ]] ; then + echo "::error::Can't extract base image info" + exit 1 + fi + + echo "version=$version" >> $GITHUB_OUTPUT + echo "dockerfile=$docker_file" >> $GITHUB_OUTPUT + echo "baseimage=$base_image" >> $GITHUB_OUTPUT + + echo -e "\033[34mVersion:\033[0m $version" + echo -e "\033[34mDockerfile:\033[0m $docker_file" + echo -e "\033[34mBase image:\033[0m $base_image" + + - name: Check if build/rebuild is required + id: build_check + run: | + if [[ "${{github.event_name}}" == "release" ]] ; then + echo "build=true" >> $GITHUB_OUTPUT + exit 0 + fi + + if [[ "${{ github.event.inputs.force_rebuild }}" == "true" ]] ; then + echo "::warning::Rebuild is required (reason: forced rebuild)" + echo "build=true" >> $GITHUB_OUTPUT + exit 0 + fi + + echo -e "::group::\033[34mDownloading built image…\033[0m" + + if ! docker pull ghcr.io/${{env.IMAGE_NAME}}:latest ; then + echo "::error::Can't download image ghcr.io/${{env.IMAGE_NAME}}:latest" + exit 1 + fi + + echo "::endgroup::" + echo -e "::group::\033[34mDownloading base image…\033[0m" + + if ! docker pull ${{steps.metadata.outputs.baseimage}} ; then + echo "::error::Can't download image ${{steps.metadata.outputs.baseimage}}" + exit 1 + fi + + echo "::endgroup::" + + base_layer=$(docker inspect "${{steps.metadata.outputs.baseimage}}" | jq -r '.[0].RootFS.Layers[-1]') + + if [[ -z "$base_layer" ]] ; then + echo "::error::Can't extract layers info from base image" + exit 1 + fi + + if ! docker inspect "ghcr.io/${{env.IMAGE_NAME}}:latest" | jq -r '.[0].RootFS.Layers' | grep -q "$base_layer" ; then + echo "::warning::Rebuild image (reason: base image rebuilt)" + echo "build=true" >> $GITHUB_OUTPUT + exit 0 + fi + + - name: Build and push Docker images (Docker) + if: ${{ steps.build_check.outputs.build == 'true' }} + uses: docker/build-push-action@v5 + with: + push: true + context: . + file: ${{steps.metadata.outputs.dockerfile}} + build-args: | + REGISTRY=docker.io + tags: | + ${{env.IMAGE_NAME}}:${{steps.metadata.outputs.version}} + ${{env.IMAGE_NAME}}:latest + + - name: Build and push Docker images (GHCR) + if: ${{ steps.build_check.outputs.build == 'true' }} + uses: docker/build-push-action@v5 + with: + push: true + context: . + file: ${{steps.metadata.outputs.dockerfile}} + build-args: | + REGISTRY=ghcr.io + tags: | + ghcr.io/${{env.IMAGE_NAME}}:${{steps.metadata.outputs.version}} + ghcr.io/${{env.IMAGE_NAME}}:latest + + - name: Show info about built Docker image + if: ${{ steps.build_check.outputs.build == 'true' }} + uses: essentialkaos/docker-info-action@v1 + with: + image: ghcr.io/${{env.IMAGE_NAME}}:latest + show-labels: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b8521f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/siocrypt +/vendor diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 0000000..55aead8 --- /dev/null +++ b/.typos.toml @@ -0,0 +1,2 @@ +[files] +extend-exclude = ["go.sum"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..12fb719 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 ESSENTIAL KAOS + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b013de4 --- /dev/null +++ b/Makefile @@ -0,0 +1,114 @@ +################################################################################ + +# This Makefile generated by GoMakeGen 3.0.2 using next command: +# gomakegen --mod . +# +# More info: https://kaos.sh/gomakegen + +################################################################################ + +ifdef VERBOSE ## Print verbose information (Flag) +VERBOSE_FLAG = -v +endif + +COMPAT ?= 1.19 +MAKEDIR = $(dir $(realpath $(firstword $(MAKEFILE_LIST)))) +GITREV ?= $(shell test -s $(MAKEDIR)/.git && git rev-parse --short HEAD) + +################################################################################ + +.DEFAULT_GOAL := help +.PHONY = fmt vet all install uninstall clean deps update init vendor mod-init mod-update mod-download mod-vendor help + +################################################################################ + +all: siocrypt ## Build all binaries + +siocrypt: + @echo "Building siocrypt…" + @go build $(VERBOSE_FLAG) -ldflags="-X main.gitrev=$(GITREV)" siocrypt.go + +install: ## Install all binaries + @echo "Installing binaries…" + @cp siocrypt /usr/bin/siocrypt + +uninstall: ## Uninstall all binaries + @echo "Removing installed binaries…" + @rm -f /usr/bin/siocrypt + +init: mod-init ## Initialize new module + +deps: mod-download ## Download dependencies + +update: mod-update ## Update dependencies to the latest versions + +vendor: mod-vendor ## Make vendored copy of dependencies + +mod-init: + @echo "[1/2] Modules initialization…" +ifdef MODULE_PATH ## Module path for initialization (String) + @go mod init $(MODULE_PATH) +else + @go mod init +endif + + @echo "[2/2] Dependencies cleanup…" +ifdef COMPAT ## Compatible Go version (String) + @go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) -go=$(COMPAT) +else + @go mod tidy $(VERBOSE_FLAG) +endif + +mod-update: + @echo "[1/4] Updating dependencies…" +ifdef UPDATE_ALL ## Update all dependencies (Flag) + @go get -u $(VERBOSE_FLAG) all +else + @go get -u $(VERBOSE_FLAG) ./... +endif + + @echo "[2/4] Stripping toolchain info…" + @grep -q 'toolchain ' go.mod && go mod edit -toolchain=none || : + + @echo "[3/4] Dependencies cleanup…" +ifdef COMPAT + @go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) +else + @go mod tidy $(VERBOSE_FLAG) +endif + + @echo "[4/4] Updating vendored dependencies…" + @test -d vendor && rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || : + +mod-download: + @echo "Downloading dependencies…" + @go mod download + +mod-vendor: + @echo "Vendoring dependencies…" + @rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || : + +fmt: ## Format source code with gofmt + @echo "Formatting sources…" + @find . -name "*.go" -exec gofmt -s -w {} \; + +vet: ## Runs 'go vet' over sources + @echo "Running 'go vet' over sources…" + @go vet -composites=false -printfuncs=LPrintf,TLPrintf,TPrintf,log.Debug,log.Info,log.Warn,log.Error,log.Critical,log.Print ./... + +clean: ## Remove generated files + @echo "Removing built binaries…" + @rm -f siocrypt + +help: ## Show this info + @echo -e '\n\033[1mTargets:\033[0m\n' + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \ + | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[33m%-9s\033[0m %s\n", $$1, $$2}' + @echo -e '\n\033[1mVariables:\033[0m\n' + @grep -E '^ifdef [A-Z_]+ .*?## .*$$' $(abspath $(lastword $(MAKEFILE_LIST))) \ + | sed 's/ifdef //' \ + | awk 'BEGIN {FS = " .*?## "}; {printf " \033[32m%-11s\033[0m %s\n", $$1, $$2}' + @echo -e '' + @echo -e '\033[90mGenerated by GoMakeGen 3.0.2\033[0m\n' + +################################################################################ diff --git a/README.md b/README.md index 5c94a1b..67f7f1d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,92 @@ -# siocrypt -Tool for encrypting/decrypting arbitrary data streams +

+ +

+ GoReportCard + Code Climate Maintainability + Codebeat badge + GitHub Actions CI Status + GitHub Actions CodeQL Status + +

+ +

Installation • Command-line completion • Man documentation • Usage • CI Status • Contributing • License

+ +
+ +`siocrypt` is a tool for encrypting/decrypting arbitrary data streams. + +### Installation + +#### From source + +To build the `siocrypt` from scratch, make sure you have a working Go 1.20+ workspace (_[instructions](https://go.dev/doc/install)_), then: + +``` +go install github.com/essentialkaos/siocrypt@latest +``` + +#### Container Image + +The latest version of `siocrypt` also available as container image on [GitHub Container Registry](https://kaos.sh/p/siocrypt) and [Docker Hub](https://kaos.sh/d/siocrypt): + +```bash +podman run --rm -it ghcr.io/essentialkaos/siocrypt:latest +# or +docker run --rm -it ghcr.io/essentialkaos/siocrypt:latest +``` + +#### Prebuilt binaries + +You can download prebuilt binaries for Linux and macOS from [EK Apps Repository](https://apps.kaos.st/siocrypt/latest): + +```bash +bash <(curl -fsSL https://apps.kaos.st/get) siocrypt +``` + +### Command-line completion + +You can generate completion for `bash`, `zsh` or `fish` shell. + +Bash: +```bash +sudo siocrypt --completion=bash 1> /etc/bash_completion.d/siocrypt +``` + +ZSH: +```bash +sudo siocrypt --completion=zsh 1> /usr/share/zsh/site-functions/siocrypt +``` + +Fish: +```bash +sudo siocrypt --completion=fish 1> /usr/share/fish/vendor_completions.d/siocrypt.fish +``` + +### Man documentation + +You can generate man page using next command: + +```bash +siocrypt --generate-man | sudo gzip > /usr/share/man/man1/siocrypt.1.gz +``` + +### Usage + +

+ +### CI Status + +| Branch | Status | +|--------|----------| +| `master` | [![CI](https://kaos.sh/w/siocrypt/ci.svg?branch=master)](https://kaos.sh/w/siocrypt/ci?query=branch:master) | +| `develop` | [![CI](https://kaos.sh/w/siocrypt/ci.svg?branch=develop)](https://kaos.sh/w/siocrypt/ci?query=branch:develop) | + +### Contributing + +Before contributing to this project please read our [Contributing Guidelines](https://github.com/essentialkaos/contributing-guidelines#contributing-guidelines). + +### License + +[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) + +

diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f42c71e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,36 @@ +# Security Policies and Procedures + +This document outlines security procedures and general policies for all +ESSENTIAL KAOS projects. + + * [Reporting a Bug](#reporting-a-bug) + * [Disclosure Policy](#disclosure-policy) + +## Reporting a Bug + +The ESSENTIAL KAOS team and community take all security bugs in our projects +very seriously. Thank you for improving the security of our project. We +appreciate your efforts and responsible disclosure and will make every effort +to acknowledge your contributions. + +Report security bugs by emailing our security team at security@essentialkaos.com. + +The security team will acknowledge your email within 48 hours and will send a +more detailed response within 48 hours, indicating the next steps in handling +your report. After the initial reply to your report, the security team will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. + +Report security bugs in third-party dependencies to the person or team +maintaining the dependencies. + +## Disclosure Policy + +When the security team receives a security bug report, they will assign it to a +primary handler. This person will coordinate the fix and release process, +involving the following steps: + + * Confirm the problem and determine the affected versions; + * Audit code to find any similar potential problems; + * Prepare fixes for all releases still under maintenance. These fixes will be + released as fast as possible. diff --git a/cli/cli.go b/cli/cli.go new file mode 100644 index 0000000..0ac4f8e --- /dev/null +++ b/cli/cli.go @@ -0,0 +1,468 @@ +package cli + +// ////////////////////////////////////////////////////////////////////////////////// // +// // +// Copyright (c) 2024 ESSENTIAL KAOS // +// Apache License, Version 2.0 // +// // +// ////////////////////////////////////////////////////////////////////////////////// // + +import ( + "crypto/rand" + "fmt" + "io" + "os" + "strings" + + "github.com/essentialkaos/ek/v12/errutil" + "github.com/essentialkaos/ek/v12/fmtc" + "github.com/essentialkaos/ek/v12/fsutil" + "github.com/essentialkaos/ek/v12/options" + "github.com/essentialkaos/ek/v12/secstr" + "github.com/essentialkaos/ek/v12/support" + "github.com/essentialkaos/ek/v12/support/deps" + "github.com/essentialkaos/ek/v12/system/procname" + "github.com/essentialkaos/ek/v12/terminal" + "github.com/essentialkaos/ek/v12/terminal/tty" + "github.com/essentialkaos/ek/v12/usage" + "github.com/essentialkaos/ek/v12/usage/completion/bash" + "github.com/essentialkaos/ek/v12/usage/completion/fish" + "github.com/essentialkaos/ek/v12/usage/completion/zsh" + "github.com/essentialkaos/ek/v12/usage/man" + "github.com/essentialkaos/ek/v12/usage/update" + + "golang.org/x/crypto/scrypt" + + "github.com/essentialkaos/sio" +) + +// ////////////////////////////////////////////////////////////////////////////////// // + +// Basic utility info +const ( + APP = "siocrypt" + VER = "0.0.1" + DESC = "Tool for encrypting/decrypting arbitrary data streams" +) + +// ////////////////////////////////////////////////////////////////////////////////// // + +// Options +const ( + OPT_DECRYPT = "D:decrypt" + OPT_CIPHER = "c:cipher" + OPT_PASSWORD = "p:password" + OPT_NO_COLOR = "nc:no-color" + OPT_HELP = "h:help" + OPT_VER = "v:version" + + OPT_VERB_VER = "vv:verbose-version" + OPT_COMPLETION = "completion" + OPT_GENERATE_MAN = "generate-man" +) + +const ( + CIPHER_AES256 = "AES256" // AES-256 GCM + CIPHER_C20P1305 = "C20P1305" // ChaCha20 Poly1305 +) + +// ////////////////////////////////////////////////////////////////////////////////// // + +// optMap contains information about all supported options +var optMap = options.Map{ + OPT_DECRYPT: {Type: options.BOOL}, + OPT_CIPHER: {}, + OPT_PASSWORD: {}, + OPT_NO_COLOR: {Type: options.BOOL}, + OPT_HELP: {Type: options.BOOL}, + OPT_VER: {Type: options.MIXED}, + + OPT_VERB_VER: {Type: options.BOOL}, + OPT_COMPLETION: {}, + OPT_GENERATE_MAN: {Type: options.BOOL}, +} + +// color tags for app name and version +var colorTagApp, colorTagVer string + +// password is secure string with password +var password *secstr.String + +// removeOutputOnError is flag to remove output file on error +var removeOutputOnError bool + +// ////////////////////////////////////////////////////////////////////////////////// // + +// Run is main utility function +func Run(gitRev string, gomod []byte) { + preConfigureUI() + + args, errs := options.Parse(optMap) + + if !errs.IsEmpty() { + terminal.Error("Options parsing errors:") + terminal.Error(errs.String()) + os.Exit(1) + } + + configureUI() + + switch { + case options.Has(OPT_COMPLETION): + os.Exit(printCompletion()) + case options.Has(OPT_GENERATE_MAN): + printMan() + os.Exit(0) + case options.GetB(OPT_VER): + genAbout(gitRev).Print(options.GetS(OPT_VER)) + os.Exit(0) + case options.GetB(OPT_VERB_VER): + support.Collect(APP, VER). + WithRevision(gitRev). + WithDeps(deps.Extract(gomod)). + Print() + os.Exit(0) + case options.GetB(OPT_HELP) || (!hasStdinData() && len(args) == 0): + genUsage().Print() + os.Exit(0) + } + + err := errutil.Chain( + processPassword, + validateOptions, + ) + + if err != nil { + terminal.Error(err) + os.Exit(1) + } + + err = process(args) + + if err != nil { + terminal.Error(err) + os.Exit(1) + } +} + +// ////////////////////////////////////////////////////////////////////////////////// // + +// preConfigureUI preconfigures UI based on information about user terminal +func preConfigureUI() { + if !tty.IsTTY() { + fmtc.DisableColors = true + } + + switch { + case fmtc.IsTrueColorSupported(): + colorTagApp, colorTagVer = "{*}{#6100DC}", "{#6100DC}" + case fmtc.Is256ColorsSupported(): + colorTagApp, colorTagVer = "{*}{#56}", "{#56}" + default: + colorTagApp, colorTagVer = "{*}{c}", "{c}" + } +} + +// configureUI configures user interface +func configureUI() { + if options.GetB(OPT_NO_COLOR) { + fmtc.DisableColors = true + } +} + +// processPassword tries to securily read password from options or env vars +func processPassword() error { + var err error + + pwd := options.GetS(OPT_PASSWORD) + + if pwd != "" { + err = procname.Replace(pwd, strings.Repeat("*", len(pwd))) + + if err != nil { + return fmt.Errorf("Can't hide provided password: %v", err) + } + } else if os.Getenv("SIOCRYPT_PASSWORD") != "" { + pwd = os.Getenv("SIOCRYPT_PASSWORD") + os.Setenv("SIOCRYPT_PASSWORD", "") + } + + if pwd == "" { + return fmt.Errorf("Password is not set") + } + + password, err = secstr.NewSecureString(pwd) + + if err != nil { + return fmt.Errorf("Can't create secure string for password: %v", err) + } + + return nil +} + +// validateOptions validates options +func validateOptions() error { + if options.Has(OPT_CIPHER) { + switch strings.ToUpper(options.GetS(OPT_CIPHER)) { + case CIPHER_AES256, CIPHER_C20P1305: + // ok + default: + return fmt.Errorf("Unsupported cipher suite %q", options.GetS(OPT_CIPHER)) + } + } + + return nil +} + +// process starts arguments processing +func process(args options.Arguments) error { + input, output, err := getIO(args) + + if err != nil { + return err + } + + key, err := deriveKey(input, output) + + if err != nil { + return err + } + + cfg := sio.Config{Key: key, CipherSuites: getCipherSuite()} + + if options.GetB(OPT_DECRYPT) { + _, err = sio.Decrypt(output, input, cfg) + + if err != nil { + cleanupOutput(output.Name()) + return fmt.Errorf("Error while decrypting data: %v", err) + } + } else { + _, err = sio.Encrypt(output, input, cfg) + + if err != nil { + cleanupOutput(output.Name()) + return fmt.Errorf("Error while encrypting data: %v", err) + } + } + + return nil +} + +// getIO returns input and output targets +func getIO(args options.Arguments) (*os.File, *os.File, error) { + var err error + var input, output *os.File + var inputFile, outputFile string + + switch len(args) { + case 0: + input = os.Stdin + output = os.Stdout + case 1: + inputFile = args.Get(0).Clean().String() + output = os.Stdout + default: + if args.Get(0).Is("--") { + input = os.Stdin + } else { + inputFile = args.Get(0).Clean().String() + } + + outputFile = args.Get(1).String() + } + + if inputFile != "" { + err = fsutil.ValidatePerms("FRS", inputFile) + + if err != nil { + return nil, nil, fmt.Errorf("Can't use given input: %v", err) + } + + input, err = os.OpenFile(inputFile, os.O_RDONLY, 0) + + if err != nil { + return nil, nil, fmt.Errorf("Can't use given input: %v", err) + } + } + + if outputFile != "" { + output, err = os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY, 0600) + + if err != nil { + return nil, nil, fmt.Errorf("Can't use given output: %v", err) + } + + removeOutputOnError = true + } + + return input, output, err +} + +// deriveKey creates derived key from password and salt +func deriveKey(input, output *os.File) ([]byte, error) { + salt := make([]byte, 32) + + if options.GetB(OPT_DECRYPT) { + _, err := io.ReadFull(input, salt) + + if err != nil { + return nil, fmt.Errorf("Can't read salt from encrypted data: %v", err) + } + } else { + _, err := io.ReadFull(rand.Reader, salt) + + if err != nil { + return nil, fmt.Errorf("Can't generate random salt: %v", err) + } + + _, err = output.Write(salt) + + if err != nil { + return nil, fmt.Errorf("Can't write salt to output: %v", err) + } + } + + key, err := scrypt.Key(password.Data, salt, 32768, 16, 1, 32) + + if err != nil { + return nil, fmt.Errorf("Can't derive key from password: %v", err) + } + + password.Destroy() + + return key, nil +} + +// getCipherSuite returns target cipher suite +func getCipherSuite() []byte { + switch strings.ToUpper(options.GetS(OPT_CIPHER)) { + case CIPHER_AES256: + return []byte{sio.AES_256_GCM} + case CIPHER_C20P1305: + return []byte{sio.CHACHA20_POLY1305} + } + + return []byte{} +} + +// hasStdinData return true if there is some data in stdin +func hasStdinData() bool { + stdin, err := os.Stdin.Stat() + + if err != nil { + return false + } + + if stdin.Mode()&os.ModeCharDevice != 0 { + return false + } + + return true +} + +// cleanupOutput removes output file on error +func cleanupOutput(file string) { + if removeOutputOnError { + os.Remove(file) + } +} + +// ////////////////////////////////////////////////////////////////////////////////// // + +// printCompletion prints completion for given shell +func printCompletion() int { + info := genUsage() + + switch options.GetS(OPT_COMPLETION) { + case "bash": + fmt.Print(bash.Generate(info, APP)) + case "fish": + fmt.Print(fish.Generate(info, APP)) + case "zsh": + fmt.Print(zsh.Generate(info, optMap, APP)) + default: + return 1 + } + + return 0 +} + +// printMan prints man page +func printMan() { + fmt.Println(man.Generate(genUsage(), genAbout(""))) +} + +// genUsage generates usage info +func genUsage() *usage.Info { + info := usage.NewInfo("", "?input", "?output") + + info.AppNameColorTag = colorTagApp + + info.Spoiler = ` Without an input file, tool reads data from standard input and writes to standard + output if no output file is specified. + + Password provided via {g}--password{!}/{g}-p{!} option will be masked in process command. Also, + password can't be specified using {b}SIOCRYPT_PASSWORD{!} environment variable.` + + info.AddOption(OPT_DECRYPT, "Decrypt data") + info.AddOption(OPT_PASSWORD, "Password for encrypting/decrypting", "?password") + info.AddOption(OPT_CIPHER, "Cipher to use {s}(AES256/C20P1305){!}", "cipher") + info.AddOption(OPT_NO_COLOR, "Disable colors in output") + info.AddOption(OPT_HELP, "Show this help message") + info.AddOption(OPT_VER, "Show version") + + info.AddRawExample( + "cat data.enc | siocrypt -p TeSt1234 | grep John", + "Read data from standard input and grep over decrypted output", + ) + + info.AddRawExample( + "cat data.enc | siocrypt -p TeSt1234 -- data.txt", + "Read data from standard input and save decrypted data as data.txt", + ) + + info.AddExample( + "-p TeSt1234 data.enc | grep John", + "Read data from file data.enc and grep over decrypted output", + ) + + info.AddExample( + "-p TeSt1234 data.enc data.txt", + "Read data from file data.enc and save decrypted data as data.txt", + ) + + info.AddRawExample( + "SIOCRYPT_PASSWORD=TeSt1234 siocrypt data.enc data.txt", + "Use password from environment variable while decrypting data", + ) + + return info +} + +// genAbout generates info about version +func genAbout(gitRev string) *usage.About { + about := &usage.About{ + App: APP, + Version: VER, + Desc: DESC, + Year: 2009, + Owner: "ESSENTIAL KAOS", + + AppNameColorTag: colorTagApp, + VersionColorTag: colorTagVer, + DescSeparator: "{s}—{!}", + + License: "Apache License, Version 2.0 ", + BugTracker: "https://github.com/essentialkaos/siocrypt/issues", + UpdateChecker: usage.UpdateChecker{"essentialkaos/siocrypt", update.GitHubChecker}, + } + + if gitRev != "" { + about.Build = "git:" + gitRev + } + + return about +} + +// ////////////////////////////////////////////////////////////////////////////////// // diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..262ade5 --- /dev/null +++ b/go.mod @@ -0,0 +1,14 @@ +module github.com/essentialkaos/siocrypt + +go 1.19 + +require ( + github.com/essentialkaos/ek/v12 v12.127.0 + github.com/essentialkaos/sio v1.0.0 + golang.org/x/crypto v0.24.0 +) + +require ( + github.com/essentialkaos/depsy v1.3.0 // indirect + golang.org/x/sys v0.21.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..3609056 --- /dev/null +++ b/go.sum @@ -0,0 +1,14 @@ +github.com/essentialkaos/check v1.4.0 h1:kWdFxu9odCxUqo1NNFNJmguGrDHgwi3A8daXX1nkuKk= +github.com/essentialkaos/depsy v1.3.0 h1:CN7bRgBU2jGTHSkg/Sh38eDUn7cvmaTp2sxFt2HpFeU= +github.com/essentialkaos/depsy v1.3.0/go.mod h1:kpiTAV17dyByVnrbNaMcZt2jRwvuXClUYOzpyJQwtG8= +github.com/essentialkaos/ek/v12 v12.127.0 h1:fU5A+QbIZ7NTq1K5jGVwAWwuLtBUhsIKuRWYT78hE+Q= +github.com/essentialkaos/ek/v12 v12.127.0/go.mod h1:71IJ7m82hgjrvWnhL+z0vIhguxz47/rfVma5/CeI5Fw= +github.com/essentialkaos/sio v1.0.0 h1:+VZg0Z7+Cx8F/FmlczzTJYM6rq/LhTR45Rsditmu0Ec= +github.com/essentialkaos/sio v1.0.0/go.mod h1:lKaW6IPMJ8GAEAiXe175zcEld370u3Nr546c22Kw5C8= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= +golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/siocrypt.go b/siocrypt.go new file mode 100644 index 0000000..75a2ee8 --- /dev/null +++ b/siocrypt.go @@ -0,0 +1,28 @@ +package main + +// ////////////////////////////////////////////////////////////////////////////////// // +// // +// Copyright (c) 2024 ESSENTIAL KAOS // +// Apache License, Version 2.0 // +// // +// ////////////////////////////////////////////////////////////////////////////////// // + +import ( + _ "embed" + + CLI "github.com/essentialkaos/siocrypt/cli" +) + +// ////////////////////////////////////////////////////////////////////////////////// // + +//go:embed go.mod +var gomod []byte + +// gitrev is short hash of the latest git commit +var gitrev string + +// ////////////////////////////////////////////////////////////////////////////////// // + +func main() { + CLI.Run(gitrev, gomod) +} From 3e923acf50b2591877b2cda671573c643236405f Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Sat, 22 Jun 2024 01:50:53 +0300 Subject: [PATCH 2/5] Update app color --- .github/images/card.svg | 2 +- .github/images/usage.svg | 2 +- README.md | 1 - cli/cli.go | 6 +++--- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/.github/images/card.svg b/.github/images/card.svg index 1396f34..f6c5134 100644 --- a/.github/images/card.svg +++ b/.github/images/card.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/.github/images/usage.svg b/.github/images/usage.svg index 9db8839..25dc085 100644 --- a/.github/images/usage.svg +++ b/.github/images/usage.svg @@ -55,7 +55,7 @@ Terminal - Usage: siocrypt {options} input output + Usage: siocrypt {options} input output Without an input file, tool reads data from standard input and writes to standard output if no output file is specified. Password provided via --password/-p option will be masked in process command. Also, diff --git a/README.md b/README.md index 67f7f1d..0ebc205 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,6 @@

- GoReportCard Code Climate Maintainability Codebeat badge GitHub Actions CI Status diff --git a/cli/cli.go b/cli/cli.go index 0ac4f8e..995c1b1 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -155,11 +155,11 @@ func preConfigureUI() { switch { case fmtc.IsTrueColorSupported(): - colorTagApp, colorTagVer = "{*}{#6100DC}", "{#6100DC}" + colorTagApp, colorTagVer = "{*}{#87D787}", "{#87D787}" case fmtc.Is256ColorsSupported(): - colorTagApp, colorTagVer = "{*}{#56}", "{#56}" + colorTagApp, colorTagVer = "{*}{#114}", "{#114}" default: - colorTagApp, colorTagVer = "{*}{c}", "{c}" + colorTagApp, colorTagVer = "{*}{g}", "{g}" } } From 9e2a19df5631ed324e125033d51d6168617ff7d2 Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Sat, 22 Jun 2024 01:57:42 +0300 Subject: [PATCH 3/5] Improve README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0ebc205..f2a8216 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,13 @@
-`siocrypt` is a tool for encrypting/decrypting arbitrary data streams. +`siocrypt` is a tool for encrypting/decrypting arbitrary data streams using [Data At Rest Encryption](https://github.com/essentialkaos/sio/blob/master/DARE.md) (_DARE_). ### Installation #### From source -To build the `siocrypt` from scratch, make sure you have a working Go 1.20+ workspace (_[instructions](https://go.dev/doc/install)_), then: +To build the `siocrypt` from scratch, make sure you have a working Go 1.21+ workspace (_[instructions](https://go.dev/doc/install)_), then: ``` go install github.com/essentialkaos/siocrypt@latest From 42694bac10139aed4cb469d7976bc842c228f1b4 Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Sat, 22 Jun 2024 15:35:50 +0300 Subject: [PATCH 4/5] Improvements --- cli/cli.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cli/cli.go b/cli/cli.go index 995c1b1..e95a9af 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -182,6 +182,8 @@ func processPassword() error { if err != nil { return fmt.Errorf("Can't hide provided password: %v", err) } + + options.Delete(OPT_PASSWORD) } else if os.Getenv("SIOCRYPT_PASSWORD") != "" { pwd = os.Getenv("SIOCRYPT_PASSWORD") os.Setenv("SIOCRYPT_PASSWORD", "") From 9084c565810325af101f02b1b84933dcb7e2476a Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Sat, 22 Jun 2024 15:44:30 +0300 Subject: [PATCH 5/5] Update card --- .github/images/card.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/images/card.svg b/.github/images/card.svg index f6c5134..4cc68ea 100644 --- a/.github/images/card.svg +++ b/.github/images/card.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file