diff --git a/.ci/boot_race/a.toml b/.ci/boot_race/a.toml index d8e69fc1..439966a5 100644 --- a/.ci/boot_race/a.toml +++ b/.ci/boot_race/a.toml @@ -3,11 +3,6 @@ secret_key = "rp-a-secret-key" listen = ["127.0.0.1:9999"] verbosity = "Verbose" -[api] -listen_path = [] -listen_fd = [] -stream_fd = [] - [[peers]] public_key = "rp-b-public-key" endpoint = "127.0.0.1:9998" diff --git a/.ci/boot_race/b.toml b/.ci/boot_race/b.toml index b7609759..52f43f14 100644 --- a/.ci/boot_race/b.toml +++ b/.ci/boot_race/b.toml @@ -3,11 +3,6 @@ secret_key = "rp-b-secret-key" listen = ["127.0.0.1:9998"] verbosity = "Verbose" -[api] -listen_path = [] -listen_fd = [] -stream_fd = [] - [[peers]] public_key = "rp-a-public-key" endpoint = "127.0.0.1:9999" diff --git a/.ci/gen-workflow-files.nu b/.ci/gen-workflow-files.nu index f1eaeece..f3b3ff8e 100755 --- a/.ci/gen-workflow-files.nu +++ b/.ci/gen-workflow-files.nu @@ -32,9 +32,9 @@ let systems_map = { # aarch64-darwin # aarch64-linux - i686-linux: ubuntu-latest, + i686-linux: ubicloud-standard-2-ubuntu-2204, x86_64-darwin: macos-13, - x86_64-linux: ubuntu-latest + x86_64-linux: ubicloud-standard-2-ubuntu-2204 } let targets = (get-attr-names ".#packages" @@ -61,14 +61,13 @@ mut release_workflow = { let runner_setup = [ { - uses: "actions/checkout@v3" + uses: "actions/checkout@v4" } { - uses: "cachix/install-nix-action@v22", - with: { nix_path: "nixpkgs=channel:nixos-unstable" } + uses: "cachix/install-nix-action@v30", } { - uses: "cachix/cachix-action@v12", + uses: "cachix/cachix-action@v15", with: { name: rosenpass, authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" @@ -154,7 +153,7 @@ for system in ($targets | columns) { } { name: Release, - uses: "softprops/action-gh-release@v1", + uses: "softprops/action-gh-release@v2", with: { draft: "${{ contains(github.ref_name, 'rc') }}", prerelease: "${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') }}", @@ -182,7 +181,7 @@ $cachix_workflow.jobs = ($cachix_workflow.jobs | insert $"($system)---whitepaper } { name: "Deploy PDF artifacts", - uses: "peaceiris/actions-gh-pages@v3", + uses: "peaceiris/actions-gh-pages@v4", with: { github_token: "${{ secrets.GITHUB_TOKEN }}", publish_dir: result/, diff --git a/.dockerignore b/.dockerignore new file mode 120000 index 00000000..3e4e48b0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +.gitignore \ No newline at end of file diff --git a/.github/workflows/bench-primitives.yml b/.github/workflows/bench-primitives.yml new file mode 100644 index 00000000..b4d9da42 --- /dev/null +++ b/.github/workflows/bench-primitives.yml @@ -0,0 +1,103 @@ +name: rosenpass-ciphers - primitives - benchmark + +permissions: + contents: write + +on: + #pull_request: + push: + +env: + CARGO_TERM_COLOR: always + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + prim-benchmark: + strategy: + fail-fast: true + matrix: + system: ["x86_64-linux", "i686-linux"] + + runs-on: ubuntu-latest + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v4 + + # Install nix + + - name: Install Nix + uses: cachix/install-nix-action@v27 # A popular action for installing Nix + with: + extra_nix_config: | + experimental-features = nix-command flakes + access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} + + # Set up environment + + - name: 🛠️ Prepare Benchmark Path + env: + EVENT_NAME: ${{ github.event_name }} + BRANCH_NAME: ${{ github.ref_name }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + case "$EVENT_NAME" in + "push") + echo "BENCH_PATH=branch/$BRANCH_NAME" >> $GITHUB_ENV + ;; + "pull_request") + echo "BENCH_PATH=pull/$PR_NUMBER" >> $GITHUB_ENV + ;; + *) + echo "don't know benchmark path for event of type $EVENT_NAME, aborting" + exit 1 + esac + + # Benchmarks ... + + - name: 🏃🏻‍♀️ Benchmarks (using Nix as shell) + working-directory: ciphers + run: nix develop ".#devShells.${{ matrix.system }}.benchmarks" --command cargo bench -F bench --bench primitives --verbose -- --output-format bencher | tee ../bench-primitives.txt + + - name: Extract benchmarks + uses: cryspen/benchmark-data-extract-transform@v2 + with: + name: rosenpass-ciphers primitives benchmarks + tool: "cargo" + os: ${{ matrix.system }} + output-file-path: bench-primitives.txt + data-out-path: bench-primitives-os.json + + - name: Fix up 'os' label in benchmark data + run: jq 'map(with_entries(.key |= if . == "os" then "operating system" else . end))' bench-primitives.json + + - name: Upload benchmarks + uses: cryspen/benchmark-upload-and-plot-action@v3 + with: + name: Crypto Primitives Benchmarks + group-by: "operating system,primitive,algorithm" + schema: "operating system,primitive,algorithm,implementation,operation,length" + input-data-path: bench-primitives.json + github-token: ${{ secrets.GITHUB_TOKEN }} + # NOTE: pushes to current repository + gh-repository: github.com/${{ github.repository }} + auto-push: true + fail-on-alert: true + base-path: benchmarks/ + + ciphers-primitives-bench-status: + if: ${{ always() }} + needs: [prim-benchmark] + runs-on: ubuntu-latest + steps: + - name: Successful + if: ${{ !(contains(needs.*.result, 'failure')) }} + run: exit 0 + - name: Failing + if: ${{ (contains(needs.*.result, 'failure')) }} + run: exit 1 diff --git a/.github/workflows/bench-protocol.yml b/.github/workflows/bench-protocol.yml new file mode 100644 index 00000000..93c98646 --- /dev/null +++ b/.github/workflows/bench-protocol.yml @@ -0,0 +1,90 @@ +name: rosenpass - protocol - benchmark + +permissions: + contents: write + +on: + #pull_request: + push: + +env: + CARGO_TERM_COLOR: always + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + proto-benchmark: + strategy: + fail-fast: true + matrix: + system: ["x86_64-linux", "i686-linux"] + + runs-on: ubuntu-latest + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v4 + + # Install nix + + - name: Install Nix + uses: cachix/install-nix-action@v27 # A popular action for installing Nix + with: + extra_nix_config: | + experimental-features = nix-command flakes + access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} + + # Set up environment + + - name: 🛠️ Prepare Benchmark Path + env: + EVENT_NAME: ${{ github.event_name }} + BRANCH_NAME: ${{ github.ref_name }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + case "$EVENT_NAME" in + "push") + echo "BENCH_PATH=branch/$BRANCH_NAME" >> $GITHUB_ENV + ;; + "pull_request") + echo "BENCH_PATH=pull/$PR_NUMBER" >> $GITHUB_ENV + ;; + *) + echo "don't know benchmark path for event of type $EVENT_NAME, aborting" + exit 1 + esac + + # Benchmarks ... + + - name: 🏃🏻‍♀️ Benchmarks + run: nix develop ".#devShells.${{ matrix.system }}.benchmarks" --command cargo bench -p rosenpass --bench trace_handshake -F trace_bench --verbose >bench-protocol.json + + - name: Upload benchmarks + uses: cryspen/benchmark-upload-and-plot-action@v3 + with: + name: Protocol Benchmarks + group-by: "operating system,architecture,protocol version,run time" + schema: "operating system,architecture,protocol version,run time,name" + input-data-path: bench-protocol.json + github-token: ${{ secrets.GITHUB_TOKEN }} + # NOTE: pushes to current repository + gh-repository: github.com/${{ github.repository }} + auto-push: true + fail-on-alert: true + base-path: benchmarks/ + + ciphers-protocol-bench-status: + if: ${{ always() }} + needs: [proto-benchmark] + runs-on: ubuntu-latest + steps: + - name: Successful + if: ${{ !(contains(needs.*.result, 'failure')) }} + run: exit 0 + - name: Failing + if: ${{ (contains(needs.*.result, 'failure')) }} + run: exit 1 diff --git a/.github/workflows/docker.yaml b/.github/workflows/docker.yaml new file mode 100644 index 00000000..cee9afca --- /dev/null +++ b/.github/workflows/docker.yaml @@ -0,0 +1,288 @@ +name: Build Docker Images + +# Run this job on all non-pull-request events, +# or if Docker-related files are changed in a pull request. +on: + push: + branches: + - "main" + tags: + - "v*" + pull_request: + paths: + - "docker/Dockerfile" + - ".github/workflows/docker.yaml" + branches: + - "main" + +permissions: + contents: read + packages: write + +jobs: + # -------------------------------- + # 1. BUILD & TEST + # -------------------------------- + build-and-test-rp: + strategy: + matrix: + arch: [amd64, arm64] + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Build (no push) and Load + id: build + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile + # no pushing here, so we can test locally + push: false + # load the built image into the local Docker daemon on the runner + load: true + target: rosenpass + tags: rosenpass:test + platforms: linux/${{ matrix.arch }} + - name: Integration Test - Standalone Key Exchange + run: | + # Create separate workdirs + mkdir -p workdir-server workdir-client + + # Create a Docker network + docker network create -d bridge rp + + echo "=== GENERATE SERVER KEYS ===" + docker run --rm \ + -v $PWD/workdir-server:/workdir \ + rosenpass:test gen-keys \ + --public-key=workdir/server-public \ + --secret-key=workdir/server-secret + + echo "=== GENERATE CLIENT KEYS ===" + docker run --rm \ + -v $PWD/workdir-client:/workdir \ + rosenpass:test gen-keys \ + --public-key=workdir/client-public \ + --secret-key=workdir/client-secret + + echo "=== SHARE PUBLIC KEYS ===" + cp workdir-client/client-public workdir-server/client-public + cp workdir-server/server-public workdir-client/server-public + + echo "=== START SERVER CONTAINER ===" + docker run -d --rm \ + --name rpserver \ + --network rp \ + -v $PWD/workdir-server:/workdir \ + rosenpass:test exchange \ + private-key workdir/server-secret \ + public-key workdir/server-public \ + listen 0.0.0.0:9999 \ + peer public-key workdir/client-public \ + outfile workdir/server-sharedkey + + # Get the container IP of the server + SERVER_IP=$(docker inspect --format='{{.NetworkSettings.Networks.rp.IPAddress}}' rpserver) + echo "SERVER_IP=$SERVER_IP" + + echo "=== START CLIENT CONTAINER ===" + docker run -d --rm \ + --name rpclient \ + --network rp \ + -v $PWD/workdir-client:/workdir \ + rosenpass:test exchange \ + private-key workdir/client-secret \ + public-key workdir/client-public \ + peer public-key workdir/server-public \ + endpoint ${SERVER_IP}:9999 \ + outfile workdir/client-sharedkey + + echo "=== COMPARE SHARED KEYS ===" + echo "Waiting up to 30 seconds for the server to generate 'server-sharedkey'..." + for i in $(seq 1 30); do + if [ -f "workdir-server/server-sharedkey" ]; then + echo "server-sharedkey found!" + break + fi + sleep 1 + done + sudo cmp workdir-server/server-sharedkey workdir-client/client-sharedkey + + echo "Standalone Key Exchange test OK." + # -------------------------------- + # 2. PUSH (only if tests pass) + # -------------------------------- + docker-image-rp: + needs: + - build-and-test-rp + # Skip if this is not a PR. Then we want to push this image. + if: ${{ github.event_name != 'pull_request' }} + # Use a matrix to build for both AMD64 and ARM64 + strategy: + matrix: + arch: [amd64, arm64] + # Switch the runner based on the architecture + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Docker meta + id: meta + + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository_owner }}/rp + labels: | + maintainer=Karolin Varner , wucke13 + org.opencontainers.image.authors=Karolin Varner , wucke13 + org.opencontainers.image.title=Rosenpass + org.opencontainers.image.description=The rp command-line integrates Rosenpass and WireGuard to help you create a VPN + org.opencontainers.image.vendor=Rosenpass e.V. + org.opencontainers.image.licenses=MIT OR Apache-2.0 + org.opencontainers.image.url=https://rosenpass.eu + org.opencontainers.image.documentation=https://rosenpass.eu/docs/ + org.opencontainers.image.source=https://github.com/rosenpass/rosenpass + + - name: Log in to registry + run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.repository_owner }} --password-stdin + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build and push by digest + id: build + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile + push: ${{ github.event_name != 'pull_request' }} + labels: ${{ steps.meta.outputs.labels }} + tags: ghcr.io/${{ github.repository_owner }}/rp + target: rp + platforms: linux/${{ matrix.arch }} + outputs: type=image,push-by-digest=true,name-canonical=true,push=true + + - name: Export digest + run: | + mkdir -p ${{ runner.temp }}/digests + digest="${{ steps.build.outputs.digest }}" + touch "${{ runner.temp }}/digests/${digest#sha256:}" + + - name: Upload digest + uses: actions/upload-artifact@v4 + with: + name: digests-rp-${{ matrix.arch }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + docker-image-rosenpass: + needs: + - build-and-test-rp + # Skip if this is not a PR. Then we want to push this image. + if: ${{ github.event_name != 'pull_request' }} + # Use a matrix to build for both AMD64 and ARM64 + strategy: + matrix: + arch: [amd64, arm64] + # Switch the runner based on the architecture + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository_owner }}/rosenpass + labels: | + maintainer=Karolin Varner , wucke13 + org.opencontainers.image.authors=Karolin Varner , wucke13 + org.opencontainers.image.title=Rosenpass + org.opencontainers.image.description=Reference implementation of the protocol rosenpass protocol + org.opencontainers.image.vendor=Rosenpass e.V. + org.opencontainers.image.licenses=MIT OR Apache-2.0 + org.opencontainers.image.url=https://rosenpass.eu + org.opencontainers.image.documentation=https://rosenpass.eu/docs/ + org.opencontainers.image.source=https://github.com/rosenpass/rosenpass + + - name: Log in to registry + run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.repository_owner }} --password-stdin + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build and push by digest + id: build + uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile + push: ${{ github.event_name != 'pull_request' }} + labels: ${{ steps.meta.outputs.labels }} + tags: ghcr.io/${{ github.repository_owner }}/rosenpass + target: rosenpass + platforms: linux/${{ matrix.arch }} + outputs: type=image,push-by-digest=true,name-canonical=true,push=true + + - name: Export digest + run: | + mkdir -p ${{ runner.temp }}/digests + digest="${{ steps.build.outputs.digest }}" + touch "${{ runner.temp }}/digests/${digest#sha256:}" + + - name: Upload digest + uses: actions/upload-artifact@v4 + with: + name: digests-rosenpass-${{ matrix.arch }} + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + merge-digests: + runs-on: ubuntu-latest + needs: + - docker-image-rosenpass + - docker-image-rp + if: ${{ github.event_name != 'pull_request' }} + strategy: + matrix: + target: [rp, rosenpass] + steps: + - name: Download digests + uses: actions/download-artifact@v4 + with: + path: ${{ runner.temp }}/digests + pattern: digests-${{ matrix.target }}-* + merge-multiple: true + + - name: Log in to registry + run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.repository_owner }} --password-stdin + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository_owner }}/${{ matrix.target }} + tags: | + type=edge,branch=main + type=sha,branch=main + type=semver,pattern={{version}} + + - name: Create manifest list and push + working-directory: ${{ runner.temp }}/digests + run: | + docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + $(printf 'ghcr.io/${{ github.repository_owner }}/${{ matrix.target }}@sha256:%s ' *) + + - name: Inspect image + run: | + docker buildx imagetools inspect ghcr.io/${{ github.repository_owner }}/${{ matrix.target }}:${{ steps.meta.outputs.version }} diff --git a/.github/workflows/manual-mac-pr.yaml b/.github/workflows/manual-mac-pr.yaml new file mode 100644 index 00000000..c11d6592 --- /dev/null +++ b/.github/workflows/manual-mac-pr.yaml @@ -0,0 +1,19 @@ +name: PR Validation on Mac +on: + workflow_dispatch: +permissions: + checks: write + contents: write +concurrency: + group: manual-mac-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + qc: + uses: ./.github/workflows/qc-mac.yaml + permissions: + checks: write + contents: read + nix: + uses: ./.github/workflows/nix-mac.yaml + permissions: + contents: write diff --git a/.github/workflows/nix-mac.yaml b/.github/workflows/nix-mac.yaml new file mode 100644 index 00000000..73e77cde --- /dev/null +++ b/.github/workflows/nix-mac.yaml @@ -0,0 +1,114 @@ +name: Nix on Mac +permissions: + contents: write +on: + push: + branches: + - main + workflow_call: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + aarch64-darwin---default: + name: Build aarch64-darwin.default + runs-on: + - warp-macos-13-arm64-6x + needs: + - aarch64-darwin---rosenpass + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + with: + nix_path: nixpkgs=channel:nixos-unstable + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Build + run: nix build .#packages.aarch64-darwin.default --print-build-logs + aarch64-darwin---release-package: + name: Build aarch64-darwin.release-package + runs-on: + - warp-macos-13-arm64-6x + needs: + - aarch64-darwin---rosenpass + - aarch64-darwin---rp + - aarch64-darwin---rosenpass-oci-image + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + with: + nix_path: nixpkgs=channel:nixos-unstable + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Build + run: nix build .#packages.aarch64-darwin.release-package --print-build-logs + aarch64-darwin---rosenpass: + name: Build aarch64-darwin.rosenpass + runs-on: + - warp-macos-13-arm64-6x + needs: [] + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + with: + nix_path: nixpkgs=channel:nixos-unstable + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Build + run: nix build .#packages.aarch64-darwin.rosenpass --print-build-logs + aarch64-darwin---rp: + name: Build aarch64-darwin.rp + runs-on: + - warp-macos-13-arm64-6x + needs: [] + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + with: + nix_path: nixpkgs=channel:nixos-unstable + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Build + run: nix build .#packages.aarch64-darwin.rp --print-build-logs + aarch64-darwin---rosenpass-oci-image: + name: Build aarch64-darwin.rosenpass-oci-image + runs-on: + - warp-macos-13-arm64-6x + needs: + - aarch64-darwin---rosenpass + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + with: + nix_path: nixpkgs=channel:nixos-unstable + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Build + run: nix build .#packages.aarch64-darwin.rosenpass-oci-image --print-build-logs + aarch64-darwin---check: + name: Run Nix checks on aarch64-darwin + runs-on: + - warp-macos-13-arm64-6x + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + with: + nix_path: nixpkgs=channel:nixos-unstable + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Check + run: nix flake check . --print-build-logs diff --git a/.github/workflows/nix.yaml b/.github/workflows/nix.yaml index 093a35e9..8efda2f0 100644 --- a/.github/workflows/nix.yaml +++ b/.github/workflows/nix.yaml @@ -15,7 +15,7 @@ jobs: i686-linux---default: name: Build i686-linux.default runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - i686-linux---rosenpass steps: @@ -32,7 +32,7 @@ jobs: i686-linux---rosenpass: name: Build i686-linux.rosenpass runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: [] steps: - uses: actions/checkout@v4 @@ -48,7 +48,7 @@ jobs: i686-linux---rosenpass-oci-image: name: Build i686-linux.rosenpass-oci-image runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - i686-linux---rosenpass steps: @@ -65,107 +65,7 @@ jobs: i686-linux---check: name: Run Nix checks on i686-linux runs-on: - - ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - - uses: cachix/cachix-action@v15 - with: - name: rosenpass - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - - name: Check - run: nix flake check . --print-build-logs - x86_64-darwin---default: - name: Build x86_64-darwin.default - runs-on: - - macos-13 - needs: - - x86_64-darwin---rosenpass - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - - uses: cachix/cachix-action@v15 - with: - name: rosenpass - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - - name: Build - run: nix build .#packages.x86_64-darwin.default --print-build-logs - x86_64-darwin---release-package: - name: Build x86_64-darwin.release-package - runs-on: - - macos-13 - needs: - - x86_64-darwin---rosenpass - - x86_64-darwin---rp - - x86_64-darwin---rosenpass-oci-image - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - - uses: cachix/cachix-action@v15 - with: - name: rosenpass - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - - name: Build - run: nix build .#packages.x86_64-darwin.release-package --print-build-logs - x86_64-darwin---rosenpass: - name: Build x86_64-darwin.rosenpass - runs-on: - - macos-13 - needs: [] - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - - uses: cachix/cachix-action@v15 - with: - name: rosenpass - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - - name: Build - run: nix build .#packages.x86_64-darwin.rosenpass --print-build-logs - x86_64-darwin---rp: - name: Build x86_64-darwin.rp - runs-on: - - macos-13 - needs: [] - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - - uses: cachix/cachix-action@v15 - with: - name: rosenpass - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - - name: Build - run: nix build .#packages.x86_64-darwin.rp --print-build-logs - x86_64-darwin---rosenpass-oci-image: - name: Build x86_64-darwin.rosenpass-oci-image - runs-on: - - macos-13 - needs: - - x86_64-darwin---rosenpass - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - - uses: cachix/cachix-action@v15 - with: - name: rosenpass - authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} - - name: Build - run: nix build .#packages.x86_64-darwin.rosenpass-oci-image --print-build-logs - x86_64-darwin---check: - name: Run Nix checks on x86_64-darwin - runs-on: - - macos-13 + - ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: cachix/install-nix-action@v30 @@ -180,7 +80,7 @@ jobs: x86_64-linux---default: name: Build x86_64-linux.default runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - x86_64-linux---rosenpass steps: @@ -197,7 +97,7 @@ jobs: x86_64-linux---proof-proverif: name: Build x86_64-linux.proof-proverif runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - x86_64-linux---proverif-patched steps: @@ -214,7 +114,7 @@ jobs: x86_64-linux---proverif-patched: name: Build x86_64-linux.proverif-patched runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: [] steps: - uses: actions/checkout@v4 @@ -230,7 +130,7 @@ jobs: x86_64-linux---release-package: name: Build x86_64-linux.release-package runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - x86_64-linux---rosenpass-static - x86_64-linux---rosenpass-static-oci-image @@ -249,7 +149,7 @@ jobs: # aarch64-linux---release-package: # name: Build aarch64-linux.release-package # runs-on: - # - ubuntu-latest + # - ubicloud-standard-2-arm-ubuntu-2204 # needs: # - aarch64-linux---rosenpass-oci-image # - aarch64-linux---rosenpass @@ -273,7 +173,7 @@ jobs: x86_64-linux---rosenpass: name: Build x86_64-linux.rosenpass runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: [] steps: - uses: actions/checkout@v4 @@ -289,7 +189,7 @@ jobs: aarch64-linux---rosenpass: name: Build aarch64-linux.rosenpass runs-on: - - ubuntu-latest + - ubicloud-standard-2-arm-ubuntu-2204 needs: [] steps: - run: | @@ -310,7 +210,7 @@ jobs: aarch64-linux---rp: name: Build aarch64-linux.rp runs-on: - - ubuntu-latest + - ubicloud-standard-2-arm-ubuntu-2204 needs: [] steps: - run: | @@ -331,7 +231,7 @@ jobs: x86_64-linux---rosenpass-oci-image: name: Build x86_64-linux.rosenpass-oci-image runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - x86_64-linux---rosenpass steps: @@ -348,7 +248,7 @@ jobs: aarch64-linux---rosenpass-oci-image: name: Build aarch64-linux.rosenpass-oci-image runs-on: - - ubuntu-latest + - ubicloud-standard-2-arm-ubuntu-2204 needs: - aarch64-linux---rosenpass steps: @@ -370,7 +270,7 @@ jobs: x86_64-linux---rosenpass-static: name: Build x86_64-linux.rosenpass-static runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: [] steps: - uses: actions/checkout@v4 @@ -386,7 +286,7 @@ jobs: x86_64-linux---rp-static: name: Build x86_64-linux.rp-static runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: [] steps: - uses: actions/checkout@v4 @@ -402,7 +302,7 @@ jobs: x86_64-linux---rosenpass-static-oci-image: name: Build x86_64-linux.rosenpass-static-oci-image runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: - x86_64-linux---rosenpass-static steps: @@ -419,7 +319,7 @@ jobs: x86_64-linux---whitepaper: name: Build x86_64-linux.whitepaper runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 needs: [] steps: - uses: actions/checkout@v4 @@ -435,7 +335,7 @@ jobs: x86_64-linux---check: name: Run Nix checks on x86_64-linux runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: cachix/install-nix-action@v30 @@ -449,7 +349,7 @@ jobs: run: nix flake check . --print-build-logs x86_64-linux---whitepaper-upload: name: Upload whitepaper x86_64-linux - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 if: ${{ github.ref == 'refs/heads/main' }} steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/qc-mac.yaml b/.github/workflows/qc-mac.yaml new file mode 100644 index 00000000..390e56e4 --- /dev/null +++ b/.github/workflows/qc-mac.yaml @@ -0,0 +1,32 @@ +name: QC Mac +on: + push: + branches: [main] + workflow_call: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + checks: write + contents: read + +jobs: + cargo-test-mac: + runs-on: warp-macos-13-arm64-6x + steps: + - uses: actions/checkout@v4 + - uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + # liboqs requires quite a lot of stack memory, thus we adjust + # the default stack size picked for new threads (which is used + # by `cargo test`) to be _big enough_. Setting it to 8 MiB + - run: RUST_MIN_STACK=8388608 cargo test --workspace --all-features diff --git a/.github/workflows/qc.yaml b/.github/workflows/qc.yaml index 5b4a9c29..94d009e5 100644 --- a/.github/workflows/qc.yaml +++ b/.github/workflows/qc.yaml @@ -14,7 +14,7 @@ permissions: jobs: prettier: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actionsx/prettier@v3 @@ -23,22 +23,38 @@ jobs: shellcheck: name: Shellcheck - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - name: Run ShellCheck uses: ludeeus/action-shellcheck@master rustfmt: - name: Rust Format - runs-on: ubuntu-latest + name: Rust code formatting + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - - name: Run Rust Formatting Script + - uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + - name: Install nightly toolchain + run: | + rustup toolchain install nightly + rustup override set nightly + - run: rustup component add rustfmt + - name: Run Cargo Fmt + run: cargo fmt --all --check + - name: Run Rust Markdown code block Formatting Script run: bash format_rust_code.sh --mode check cargo-bench: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -57,7 +73,7 @@ jobs: mandoc: name: mandoc - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - name: Install mandoc run: sudo apt-get install -y mandoc @@ -66,7 +82,7 @@ jobs: run: doc/check.sh doc/rp.1 cargo-audit: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions-rs/audit-check@v1 @@ -74,7 +90,7 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} cargo-clippy: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -93,7 +109,7 @@ jobs: args: --all-features cargo-doc: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -112,12 +128,7 @@ jobs: - run: RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --document-private-items cargo-test: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-13] - # - ubuntu is x86-64 - # - macos-13 is also x86-64 architecture + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -136,7 +147,7 @@ jobs: cargo-test-nix-devshell-x86_64-linux: runs-on: - - ubuntu-latest + - ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -158,7 +169,7 @@ jobs: - run: nix develop --command cargo test --workspace --all-features cargo-fuzz: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -173,7 +184,7 @@ jobs: - name: Install nightly toolchain run: | rustup toolchain install nightly - rustup default nightly + rustup override set nightly - name: Install cargo-fuzz run: cargo install cargo-fuzz - name: Run fuzzing @@ -191,10 +202,24 @@ jobs: cargo fuzz run fuzz_vec_secret_alloc_memfdsec_mallocfb -- -max_total_time=5 codecov: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 + env: + RUSTUP_TOOLCHAIN: nightly steps: - uses: actions/checkout@v4 - - run: rustup default nightly + - uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + - name: Install nightly toolchain + run: | + rustup toolchain install nightly + rustup override set nightly - run: rustup component add llvm-tools-preview - run: | cargo install cargo-llvm-cov || true @@ -208,5 +233,4 @@ jobs: with: files: ./target/grcov/lcov verbose: true - env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/regressions.yml b/.github/workflows/regressions.yml index a370e2f4..1f19746f 100644 --- a/.github/workflows/regressions.yml +++ b/.github/workflows/regressions.yml @@ -14,7 +14,7 @@ permissions: jobs: multi-peer: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - run: cargo build --bin rosenpass --release @@ -25,7 +25,7 @@ jobs: [ $(ls -1 output/ate/out | wc -l) -eq 100 ] boot-race: - runs-on: ubuntu-latest + runs-on: ubicloud-standard-2-ubuntu-2204 steps: - uses: actions/checkout@v4 - run: cargo build --bin rosenpass --release diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 90cc1176..8fb64135 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -13,8 +13,6 @@ jobs: steps: - uses: actions/checkout@v4 - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - uses: cachix/cachix-action@v15 with: name: rosenpass @@ -34,8 +32,6 @@ jobs: steps: - uses: actions/checkout@v4 - uses: cachix/install-nix-action@v30 - with: - nix_path: nixpkgs=channel:nixos-unstable - uses: cachix/cachix-action@v15 with: name: rosenpass @@ -69,3 +65,24 @@ jobs: draft: ${{ contains(github.ref_name, 'rc') }} prerelease: ${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') }} files: result/* + linux-packages: + name: Build and upload DEB and RPM packages + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v30 + - uses: cachix/cachix-action@v15 + with: + name: rosenpass + authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + - name: Build DEB & RPM package + run: | + mkdir packages + for f in $(nix build .#package-deb .#package-rpm --print-out-paths); do cp "$f" "packages/${f#*-}"; done + - name: Release + uses: softprops/action-gh-release@v2 + with: + draft: ${{ contains(github.ref_name, 'rc') }} + prerelease: ${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') }} + files: | + packages/* diff --git a/.github/workflows/supply-chain.yml b/.github/workflows/supply-chain.yml index 024ecbcc..998b2d9b 100644 --- a/.github/workflows/supply-chain.yml +++ b/.github/workflows/supply-chain.yml @@ -28,6 +28,10 @@ jobs: ~/.cargo/registry/cache/ ~/.cache/cargo-supply-chain/ key: cargo-supply-chain-cache + - name: Install nightly toolchain + run: | + rustup toolchain install nightly + rustup override set nightly - uses: actions/cache@v4 with: path: ${{ runner.tool_cache }}/cargo-supply-chain @@ -46,8 +50,12 @@ jobs: cargo-vet: name: Vet Dependencies runs-on: ubuntu-latest + permissions: + contents: write steps: - uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} - uses: actions/cache@v4 with: path: | @@ -55,10 +63,10 @@ jobs: ~/.cargo/registry/index/ ~/.cargo/registry/cache/ key: cargo-vet-cache - - name: Install stable toolchain # Since we are running/compiling cargo-vet, we should rely on the stable toolchain. + - name: Install nightly toolchain run: | - rustup toolchain install stable - rustup default stable + rustup toolchain install nightly + rustup override set nightly - uses: actions/cache@v4 with: path: ${{ runner.tool_cache }}/cargo-vet @@ -67,5 +75,103 @@ jobs: run: echo "${{ runner.tool_cache }}/cargo-vet/bin" >> $GITHUB_PATH - name: Ensure that the tool cache is populated with the cargo-vet binary run: cargo install --root ${{ runner.tool_cache }}/cargo-vet cargo-vet + - name: Check which event triggered this CI run, a push or a pull request. + run: | + EVENT_NAME="${{ github.event_name }}" + IS_PR="false" + IS_PUSH="false" + if [[ "$EVENT_NAME" == "pull_request" ]]; then + echo "This CI run was triggered in the context of a pull request." + IS_PR="true" + elif [[ "$EVENT_NAME" == "push" ]]; then + echo "This CI run was triggered in the context of a push." + IS_PUSH="true" + else + echo "ERROR: This CI run was not triggered in the context of a pull request or a push. Exiting with error." + exit 1 + fi + echo "IS_PR=$IS_PR" >> $GITHUB_ENV + echo "IS_PUSH=$IS_PUSH" >> $GITHUB_ENV + shell: bash + - name: Check if last commit was by Dependabot + run: | + # Depending on the trigger for, the relevant commit has to be deduced differently. + if [[ "$IS_PR" == true ]]; then + # This is the commit ID for the last commit to the head branch of the pull request. + # If we used github.sha here instead, it would point to a merge commit between the PR and the main branch, which is only created for the CI run. + SHA="${{ github.event.pull_request.head.sha }}" + REF="${{ github.head_ref }}" + elif [[ "$IS_PUSH" == "true" ]]; then + SHA="${{ github.sha }}" # This is the last commit to the branch. + REF=${GITHUB_REF#refs/heads/} + else + echo "ERROR: This action only supports pull requests and push events as triggers. Exiting with error." + exit 1 + fi + echo "Commit SHA is $SHA" + echo "Branch is $REF" + echo "REF=$REF" >> $GITHUB_ENV + + COMMIT_AUTHOR=$(gh api repos/${{ github.repository }}/commits/$SHA --jq .author.login) # .author.login might be null, but for dependabot it will always be there and cannot be spoofed in contrast to .commit.author.name + echo "The author of the last commit is $COMMIT_AUTHOR" + if [[ "$COMMIT_AUTHOR" == "dependabot[bot]" ]]; then + echo "The last commit was made by dependabot" + LAST_COMMIT_IS_BY_DEPENDABOT=true + else + echo "The last commit was made by $COMMIT_AUTHOR not by dependabot" + LAST_COMMIT_IS_BY_DEPENDABOT=false + fi + echo "LAST_COMMIT_IS_BY_DEPENDABOT=$LAST_COMMIT_IS_BY_DEPENDABOT" >> $GITHUB_ENV + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: bash + - name: Check if the last commit's message ends in "--regenerate-exemptions" + run: | + # Get commit message + COMMIT_MESSAGE=$(git log -1 --pretty=format:"%s") + if [[ "$COMMIT_MESSAGE" == *"--regenerate-exemptions" ]]; then + echo "The last commit message ends in --regenerate-exemptions" + REGEN_EXEMP=true + else + echo "The last commit message does not end in --regenerate-exemptions" + REGEN_EXEMP=false + fi + echo "REGEN_EXEMP=$REGEN_EXEMP" >> $GITHUB_ENV + shell: bash + - name: Check if the CI run happens in the context of a dependabot PR # Even if a PR is created by dependabot, the last commit can, and often should be, the regeneration of the cargo vet exemptions. It could also be from an individual making manual changes. + run: | + IN_DEPENDABOT_PR_CONTEXT="false" + if [[ $IS_PR == "true" && "${{ github.event.pull_request.user.login }}" == "dependabot[bot]" ]]; then + IN_DEPENDABOT_PR_CONTEXT="true" + echo "This CI run is in the context of PR by dependabot." + else + echo "This CI run is NOT in the context of PR by dependabot." + IN_DEPENDABOT_PR_CONTEXT="false" + fi + echo "IN_DEPENDABOT_PR_CONTEXT=$IN_DEPENDABOT_PR_CONTEXT" >> $GITHUB_ENV + shell: bash + - uses: actions/checkout@v4 + if: env.IN_DEPENDABOT_PR_CONTEXT == 'true' + with: + token: ${{ secrets.CI_BOT_PAT }} + - name: In case of a dependabot PR, ensure that we are not in a detached HEAD state + if: env.IN_DEPENDABOT_PR_CONTEXT == 'true' + run: | + git fetch origin $REF # ensure that we are up to date. + git switch $REF # ensure that we are NOT in a detached HEAD state. This is important for the commit action in the end + shell: bash + - name: Regenerate cargo vet exemptions if we are in the context of a PR created by dependabot and the last commit is by dependabot or a regeneration of cargo vet exemptions was explicitly requested. + if: env.IN_DEPENDABOT_PR_CONTEXT == 'true' && (env.LAST_COMMIT_IS_BY_DEPENDABOT == 'true' || env.REGEN_EXEMP=='true') # Run only for Dependabot PRs or if specifically requested + run: cargo vet regenerate exemptions + - name: Commit and push changes if we are in the context of a PR created by dependabot and the last commit is by dependabot or a regeneration of cargo vet exemptions was explicitly requested. + if: env.IN_DEPENDABOT_PR_CONTEXT == 'true' && (env.LAST_COMMIT_IS_BY_DEPENDABOT == 'true' || env.REGEN_EXEMP=='true') + uses: stefanzweifel/git-auto-commit-action@v6 + with: + commit_message: Regenerate cargo vet exemptions + commit_user_name: rosenpass-ci-bot[bot] + commit_user_email: noreply@rosenpass.eu + commit_author: Rosenpass CI Bot + env: + GITHUB_TOKEN: ${{ secrets.CI_BOT_PAT }} - name: Invoke cargo-vet run: cargo vet --locked diff --git a/.gitignore b/.gitignore index 4270d4ea..966c47cb 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ _markdown_* .vscode /output +.nixos-test-history diff --git a/Cargo.lock b/Cargo.lock index 486d8840..7efbdde6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,9 +60,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.15" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526" +checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" dependencies = [ "anstyle", "anstyle-parse", @@ -75,43 +75,44 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.8" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "anstyle-parse" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb" +checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a" +checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.4" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8" +checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" dependencies = [ "anstyle", - "windows-sys 0.52.0", + "once_cell", + "windows-sys 0.59.0", ] [[package]] name = "anyhow" -version = "1.0.95" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" +checksum = "6b964d184e89d9b6b67dd2715bc8e74cf3107fb2b529990c90cf517326150bf4" dependencies = [ "backtrace", ] @@ -177,7 +178,7 @@ version = "0.68.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "726e4313eb6ec35d2730258ad4e15b547ee75d6afaa1361a922e78e59b7d8078" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "cexpr", "clang-sys", "lazy_static", @@ -190,7 +191,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.87", + "syn 2.0.98", "which", ] @@ -202,9 +203,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.6.0" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" [[package]] name = "blake2" @@ -235,9 +236,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.16.0" +version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" +checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" [[package]] name = "byteorder" @@ -247,9 +248,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.7.2" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" +checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9" [[package]] name = "cast" @@ -259,9 +260,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.1.30" +version = "1.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b16803a61b81d9eabb7eae2588776c4c1e584b738ede45fdbb4c972cec1e9945" +checksum = "c736e259eea577f443d5c86c304f9f4ae0295c43f3ba05c21f1d66b5f06001af" dependencies = [ "jobserver", "libc", @@ -358,9 +359,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.23" +version = "4.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" +checksum = "92b7b18d71fad5313a1e320fa9897994228ce274b60faa4d694fe0ea89cd9e6d" dependencies = [ "clap_builder", "clap_derive", @@ -368,9 +369,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.23" +version = "4.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" +checksum = "a35db2071778a7344791a4fb4f95308b5673d219dee3ae348b86642574ecc90c" dependencies = [ "anstream", "anstyle", @@ -380,23 +381,23 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.5.40" +version = "4.5.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2e663e3e3bed2d32d065a8404024dad306e699a04263ec59919529f803aee9" +checksum = "1e3040c8291884ddf39445dc033c70abc2bc44a42f0a3a00571a0f483a83f0cd" dependencies = [ "clap", ] [[package]] name = "clap_derive" -version = "4.5.18" +version = "4.5.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" +checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -407,9 +408,9 @@ checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "clap_mangen" -version = "0.2.24" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbae9cbfdc5d4fa8711c09bd7b83f644cb48281ac35bf97af3e47b0675864bdf" +checksum = "27b4c3c54b30f0d9adcb47f25f61fcce35c4dd8916638c6b82fbd5f4fb4179e2" dependencies = [ "clap", "roff", @@ -417,9 +418,9 @@ dependencies = [ [[package]] name = "cmake" -version = "0.1.51" +version = "0.1.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb1e43aa7fd152b1f968787f7dbcdeb306d1867ff373c69955211876c053f91a" +checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" dependencies = [ "cc", ] @@ -432,9 +433,9 @@ checksum = "67ba02a97a2bd10f4b59b25c7973101c79642302776489e030cd13cdab09ed15" [[package]] name = "colorchoice" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0" +checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" [[package]] name = "command-fds" @@ -443,14 +444,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f190f3c954f7bca3c6296d0ec561c739bdbe6c7e990294ed168d415f6e1b5b01" dependencies = [ "nix 0.27.1", - "thiserror", + "thiserror 1.0.69", ] [[package]] name = "cpufeatures" -version = "0.2.14" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" dependencies = [ "libc", ] @@ -499,18 +500,18 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "crossbeam-channel" -version = "0.5.13" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.5" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -527,15 +528,15 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.20" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" +checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929" [[package]] name = "crypto-common" @@ -581,7 +582,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -629,7 +630,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.11.1", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -651,7 +652,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core 0.20.10", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -662,7 +663,7 @@ checksum = "30542c1ad912e0e3d22a1935c290e12e8a29d704a420177a31faad4a601a0800" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -704,7 +705,7 @@ dependencies = [ "darling 0.20.10", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -724,7 +725,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core 0.20.2", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -777,9 +778,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" @@ -793,9 +794,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "fiat-crypto" @@ -877,7 +878,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -932,7 +933,7 @@ dependencies = [ "netlink-packet-generic", "netlink-packet-utils", "netlink-proto", - "thiserror", + "thiserror 1.0.69", "tokio", ] @@ -945,10 +946,22 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.13.3+wasi-0.2.2", + "windows-targets 0.52.6", +] + [[package]] name = "gimli" version = "0.31.1" @@ -957,9 +970,9 @@ checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "glob" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" [[package]] name = "half" @@ -986,6 +999,82 @@ version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" +[[package]] +name = "hax-lib" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd2dddf00d9120e8ff07ec0411cd48f6f419782b53c109d3984b6bf94345c822" +dependencies = [ + "hax-lib-macros 0.1.0", + "num-bigint", + "num-traits", +] + +[[package]] +name = "hax-lib" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61933dbb676f11311378720e1ee97a511813edb7044255381ba0d625cac6be7b" +dependencies = [ + "hax-lib-macros 0.2.0", + "num-bigint", + "num-traits", +] + +[[package]] +name = "hax-lib-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "013ec0c6e58481b11658007e794ee09be35b97ef02c92102b9a5c01afd43a82f" +dependencies = [ + "hax-lib-macros-types 0.1.0", + "paste", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.98", +] + +[[package]] +name = "hax-lib-macros" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba3a8d32921c3f535e973f72053d20bc8c7f74028911a269748440952157807" +dependencies = [ + "hax-lib-macros-types 0.2.0", + "paste", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.98", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e897f0a73b06263b106327db34e77b8df37a9a94a3fba759ee7c9b69493396" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a22f64cb35f8363892df6285e7edbe96885cd660d85bfd6765c95886647b77" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + [[package]] name = "heapless" version = "0.7.17" @@ -1047,9 +1136,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "indexmap" -version = "2.6.0" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" dependencies = [ "equivalent", "hashbrown", @@ -1057,13 +1146,24 @@ dependencies = [ [[package]] name = "inout" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ "generic-array", ] +[[package]] +name = "io-uring" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d93587f37623a1a17d94ef2bc9ada592f5465fe7732084ab7beefabe5c77c0c4" +dependencies = [ + "bitflags 2.8.0", + "cfg-if", + "libc", +] + [[package]] name = "ipc-channel" version = "0.18.3" @@ -1076,7 +1176,7 @@ dependencies = [ "lazy_static", "libc", "mio", - "rand", + "rand 0.8.5", "serde", "tempfile", "uuid", @@ -1085,13 +1185,13 @@ dependencies = [ [[package]] name = "is-terminal" -version = "0.4.13" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" +checksum = "e19b23d53f35ce9f56aebc7d1bb4e6ac1e9c0db7ac85c8d1760c04379edced37" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -1111,9 +1211,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.11" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "jobserver" @@ -1126,13 +1226,23 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.72" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" dependencies = [ + "once_cell", "wasm-bindgen", ] +[[package]] +name = "keccak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" +dependencies = [ + "cpufeatures", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1147,9 +1257,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.168" +version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" +checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" [[package]] name = "libcrux" @@ -1157,11 +1267,31 @@ version = "0.0.2-pre.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31d9dcd435758db03438089760c55a45e6bcab7e4e299ee261f75225ab29d482" dependencies = [ - "getrandom", + "getrandom 0.2.15", "libcrux-hacl", "libcrux-platform", "libjade-sys", - "rand", + "rand 0.8.5", +] + +[[package]] +name = "libcrux-blake2" +version = "0.0.3-pre" +source = "git+https://github.com/cryspen/libcrux.git?rev=10ce653e9476#10ce653e94761352b657b6cecdcc0c85675813df" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros 0.0.2", +] + +[[package]] +name = "libcrux-chacha20poly1305" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78d522fb626847390ea4b776c7eca179ecec363c6c4730b61b0c0feb797b8d92" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros 0.0.2", + "libcrux-poly1305", ] [[package]] @@ -1174,6 +1304,56 @@ dependencies = [ "libcrux-platform", ] +[[package]] +name = "libcrux-hacl-rs" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8bba0885296a72555a5d77056c39cc9b04edd9ab1afa3025ef3dbd96220705c" +dependencies = [ + "libcrux-macros 0.0.2", +] + +[[package]] +name = "libcrux-intrinsics" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f764ef781467a75b92f4df575911f1cdcf77a7beb316d8054a233fed53a7ab" +dependencies = [ + "hax-lib 0.2.0", +] + +[[package]] +name = "libcrux-macros" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3021bc24fb679408d4d7175e21cf808f49816c599733ebf4a97e5bd39c3ce7c0" +dependencies = [ + "quote", + "syn 2.0.98", +] + +[[package]] +name = "libcrux-macros" +version = "0.0.3" +source = "git+https://github.com/cryspen/libcrux.git?rev=0ab6d2dd9c1f#0ab6d2dd9c1f39c82b1125a566d6befb38feea28" +dependencies = [ + "quote", + "syn 2.0.98", +] + +[[package]] +name = "libcrux-ml-kem" +version = "0.0.2-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89cbf9aad4ad38d53cfdd7ffe9041cc4cf516c8c5a6f9c1a7bb8136a82b7b6d6" +dependencies = [ + "hax-lib 0.1.0", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-sha3", + "rand 0.9.0", +] + [[package]] name = "libcrux-platform" version = "0.0.2-pre.2" @@ -1184,10 +1364,39 @@ dependencies = [ ] [[package]] -name = "libfuzzer-sys" -version = "0.4.8" +name = "libcrux-poly1305" +version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b9569d2f74e257076d8c6bfa73fb505b46b851e51ddaecc825944aa3bed17fa" +checksum = "80143d78ae14ab51ceb2c8a9514fb60af6645d42a9c951bc511792c19c974fca" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros 0.0.2", +] + +[[package]] +name = "libcrux-sha3" +version = "0.0.2-beta.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6afd802f5c7862be77f1f320df6c0fea0f09a78ca94e79df26625c60d2d96de7" +dependencies = [ + "hax-lib 0.1.0", + "libcrux-intrinsics", + "libcrux-platform", +] + +[[package]] +name = "libcrux-test-utils" +version = "0.0.2" +source = "git+https://github.com/cryspen/libcrux.git?rev=0ab6d2dd9c1f#0ab6d2dd9c1f39c82b1125a566d6befb38feea28" +dependencies = [ + "libcrux-macros 0.0.3", +] + +[[package]] +name = "libfuzzer-sys" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf78f52d400cf2d84a3a973a78a592b4adc535739e0a5597a0da6f0c357adc75" dependencies = [ "arbitrary", "cc", @@ -1205,9 +1414,9 @@ dependencies = [ [[package]] name = "libloading" -version = "0.8.5" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" +checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", "windows-targets 0.52.6", @@ -1215,9 +1424,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.4.14" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "lock_api" @@ -1231,9 +1440,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.22" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" +checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" [[package]] name = "memchr" @@ -1264,7 +1473,7 @@ name = "memsec" version = "0.6.3" source = "git+https://github.com/rosenpass/memsec.git?rev=aceb9baee8aec6844125bd6612f92e9a281373df#aceb9baee8aec6844125bd6612f92e9a281373df" dependencies = [ - "getrandom", + "getrandom 0.2.15", "libc", "windows-sys 0.45.0", ] @@ -1277,9 +1486,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.0" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5" dependencies = [ "adler2", ] @@ -1292,7 +1501,7 @@ checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" dependencies = [ "libc", "log", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", "windows-sys 0.52.0", ] @@ -1310,9 +1519,9 @@ dependencies = [ [[package]] name = "neli-proc-macros" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c168194d373b1e134786274020dae7fc5513d565ea2ebb9bc9ff17ffb69106d4" +checksum = "0c8034b7fbb6f9455b2a96c19e6edf8dc9fc34c70449938d8ee3b4df363f61fe" dependencies = [ "either", "proc-macro2", @@ -1367,7 +1576,7 @@ dependencies = [ "anyhow", "byteorder", "paste", - "thiserror", + "thiserror 1.0.69", ] [[package]] @@ -1386,24 +1595,23 @@ dependencies = [ [[package]] name = "netlink-proto" -version = "0.11.3" +version = "0.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b33524dc0968bfad349684447bfce6db937a9ac3332a1fe60c0c5a5ce63f21" +checksum = "72452e012c2f8d612410d89eea01e2d9b56205274abb35d53f60200b2ec41d60" dependencies = [ "bytes", "futures", "log", "netlink-packet-core", "netlink-sys", - "thiserror", - "tokio", + "thiserror 2.0.11", ] [[package]] name = "netlink-sys" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416060d346fbaf1f23f9512963e3e878f1a78e707cb699ba9215761754244307" +checksum = "16c903aa70590cb93691bf97a767c8d1d6122d2cc9070433deb3bbf36ce8bd23" dependencies = [ "bytes", "futures", @@ -1431,7 +1639,7 @@ version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "cfg-if", "libc", ] @@ -1446,6 +1654,25 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1457,18 +1684,18 @@ dependencies = [ [[package]] name = "object" -version = "0.36.5" +version = "0.36.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.20.2" +version = "1.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" +checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e" [[package]] name = "oorandom" @@ -1532,9 +1759,9 @@ checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" [[package]] name = "pin-project-lite" -version = "0.2.14" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "pin-utils" @@ -1606,24 +1833,48 @@ version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" dependencies = [ - "zerocopy", + "zerocopy 0.7.35", ] [[package]] name = "prettyplease" -version = "0.2.22" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479cf940fbbb3426c32c5d5176f62ad57549a0bb84773423ba8be9d089f5faba" +checksum = "6924ced06e1f7dfe3fa48d57b9f74f55d8915f5036121bef647ef4b204895fac" dependencies = [ "proc-macro2", - "syn 2.0.87", + "syn 2.0.98", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", ] [[package]] name = "proc-macro2" -version = "1.0.87" +version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3e4daa0dcf6feba26f985457cdf104d4b4256fc5a09547140f3631bb076b19a" +checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" dependencies = [ "unicode-ident", ] @@ -1645,18 +1896,18 @@ dependencies = [ [[package]] name = "psm" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa37f80ca58604976033fae9515a8a2989fc13797d953f7c04fb8fa36a11f205" +checksum = "f58e5423e24c18cc840e1c98370b3993c6649cd1678b4d24318bcf0a083cbe88" dependencies = [ "cc", ] [[package]] name = "quote" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] @@ -1668,8 +1919,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", + "zerocopy 0.8.24", ] [[package]] @@ -1679,7 +1941,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", ] [[package]] @@ -1688,7 +1960,16 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "getrandom 0.2.15", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.1", ] [[package]] @@ -1713,18 +1994,18 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.7" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +checksum = "82b568323e98e49e2a0899dcee453dd679fae22d69adf9b11dd508d1549b7e2f" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", ] [[package]] name = "regex" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38200e5ee88914975b69f657f0801b6f6dccafd44fd9326302a4aaeecfacb1d8" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", @@ -1734,9 +2015,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", @@ -1771,12 +2052,13 @@ dependencies = [ "hex", "hex-literal", "home", + "libcrux-test-utils", "log", "memoffset 0.9.1", "mio", "paste", "procspawn", - "rand", + "rand 0.8.5", "rosenpass-cipher-traits", "rosenpass-ciphers", "rosenpass-constant-time", @@ -1792,10 +2074,10 @@ dependencies = [ "static_assertions", "tempfile", "test_bin", - "thiserror", + "thiserror 1.0.69", "toml", "uds", - "zerocopy", + "zerocopy 0.7.35", "zeroize", ] @@ -1806,6 +2088,8 @@ dependencies = [ "anyhow", "rosenpass-oqs", "rosenpass-secret-memory", + "rosenpass-to", + "thiserror 1.0.69", ] [[package]] @@ -1815,13 +2099,21 @@ dependencies = [ "anyhow", "blake2", "chacha20poly1305", + "criterion", "libcrux", + "libcrux-blake2", + "libcrux-chacha20poly1305", + "libcrux-ml-kem", + "rand 0.8.5", + "rosenpass-cipher-traits", "rosenpass-constant-time", "rosenpass-oqs", "rosenpass-secret-memory", "rosenpass-to", "rosenpass-util", + "sha3", "static_assertions", + "thiserror 1.0.69", "zeroize", ] @@ -1830,7 +2122,7 @@ name = "rosenpass-constant-time" version = "0.1.0" dependencies = [ "memsec", - "rand", + "rand 0.8.5", "rosenpass-to", ] @@ -1871,7 +2163,7 @@ dependencies = [ "log", "memsec", "procspawn", - "rand", + "rand 0.8.5", "rosenpass-to", "rosenpass-util", "tempfile", @@ -1891,14 +2183,15 @@ version = "0.1.0" dependencies = [ "anyhow", "base64ct", + "libcrux-test-utils", "mio", "rustix", "static_assertions", "tempfile", - "thiserror", + "thiserror 1.0.69", "typenum", "uds", - "zerocopy", + "zerocopy 0.7.35", "zeroize", ] @@ -1915,15 +2208,15 @@ dependencies = [ "mio", "postcard", "procspawn", - "rand", + "rand 0.8.5", "rosenpass-secret-memory", "rosenpass-to", "rosenpass-util", "rustix", - "thiserror", + "thiserror 1.0.69", "tokio", "wireguard-uapi", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -1969,7 +2262,7 @@ dependencies = [ "netlink-proto", "netlink-sys", "nix 0.27.1", - "thiserror", + "thiserror 1.0.69", "tokio", ] @@ -1996,11 +2289,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.42" +version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "errno", "libc", "linux-raw-sys", @@ -2008,10 +2301,16 @@ dependencies = [ ] [[package]] -name = "ryu" -version = "1.0.18" +name = "rustversion" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" + +[[package]] +name = "ryu" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea1a2d0a644769cc99faa24c3ad26b379b786fe7c36fd3c546254801650e6dd" [[package]] name = "same-file" @@ -2024,9 +2323,9 @@ dependencies = [ [[package]] name = "scc" -version = "2.2.1" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "553f8299af7450cda9a52d3a370199904e7a46b5ffd1bef187c4a6af3bb6db69" +checksum = "ea091f6cac2595aa38993f04f4ee692ed43757035c36e67c180b6828356385b1" dependencies = [ "sdd", ] @@ -2039,41 +2338,41 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sdd" -version = "3.0.4" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49c1eeaf4b6a87c7479688c6d52b9f1153cedd3c489300564f932b065c6eab95" +checksum = "b07779b9b918cc05650cb30f404d4d7835d26df37c235eded8a6832e2fb82cca" [[package]] name = "semver" -version = "1.0.23" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" +checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03" [[package]] name = "serde" -version = "1.0.217" +version = "1.0.218" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" +checksum = "e8dfc9d19bdbf6d17e22319da49161d5d0108e4188e8b680aef6299eed22df60" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.217" +version = "1.0.218" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" +checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] name = "serde_json" -version = "1.0.128" +version = "1.0.139" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" +checksum = "44f86c3acccc9c65b153fe1b85a3be07fe5515274ec9f0653b4a0875731c72a6" dependencies = [ "itoa", "memchr", @@ -2112,7 +2411,17 @@ checksum = "5d69265a08751de7844521fd15003ae0a888e035773ba05695c5c759a6f89eef" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", +] + +[[package]] +name = "sha3" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" +dependencies = [ + "digest", + "keccak", ] [[package]] @@ -2157,18 +2466,18 @@ checksum = "88414a5ca1f85d82cc34471e975f0f74f6aa54c40f062efa42c0080e7f763f81" [[package]] name = "smallvec" -version = "1.13.2" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" [[package]] name = "socket2" -version = "0.5.7" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2188,9 +2497,9 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "stacker" -version = "0.1.17" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799c883d55abdb5e98af1a7b3f23b9b6de8ecada0ecac058672d7635eb48ca7b" +checksum = "d9156ebd5870ef293bfb43f91c7a74528d363ec0d424afe24160ed5a4343d08a" dependencies = [ "cc", "cfg-if", @@ -2236,9 +2545,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.87" +version = "2.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" dependencies = [ "proc-macro2", "quote", @@ -2253,12 +2562,13 @@ checksum = "b4e17d8598067a8c134af59cd33c1c263470e089924a11ab61cf61690919fe3b" [[package]] name = "tempfile" -version = "3.14.0" +version = "3.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" +checksum = "22e5a0acb1f3f55f65cc4a866c361b2fb2a0ff6366785ae6fbb5f85df07ba230" dependencies = [ "cfg-if", "fastrand", + "getrandom 0.3.1", "once_cell", "rustix", "windows-sys 0.59.0", @@ -2285,7 +2595,16 @@ version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" +dependencies = [ + "thiserror-impl 2.0.11", ] [[package]] @@ -2296,7 +2615,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.98", ] [[package]] @@ -2311,31 +2641,33 @@ dependencies = [ [[package]] name = "tokio" -version = "1.42.0" +version = "1.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" +checksum = "43864ed400b6043a4757a25c7a64a8efde741aed79a056a2fb348a406701bb35" dependencies = [ "backtrace", "bytes", + "io-uring", "libc", "mio", "parking_lot", "pin-project-lite", "signal-hook-registry", + "slab", "socket2", "tokio-macros", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "tokio-macros" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -2374,9 +2706,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" [[package]] name = "uds" @@ -2389,9 +2721,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.13" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" +checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" [[package]] name = "universal-hash" @@ -2411,11 +2743,11 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.10.0" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" +checksum = "93d59ca99a559661b96bf898d8fce28ed87935fd2bea9f05983c1464dd6c71b1" dependencies = [ - "getrandom", + "getrandom 0.3.1", ] [[package]] @@ -2441,36 +2773,45 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] -name = "wasm-bindgen" -version = "0.2.95" +name = "wasi" +version = "0.13.3+wasi-0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" +checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", "once_cell", + "rustversion", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.95" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" dependencies = [ "bumpalo", "log", - "once_cell", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.95" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2478,28 +2819,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.95" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.95" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] [[package]] name = "web-sys" -version = "0.3.72" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" +checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" dependencies = [ "js-sys", "wasm-bindgen", @@ -2579,7 +2923,7 @@ checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -2590,7 +2934,7 @@ checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] [[package]] @@ -2846,7 +3190,16 @@ dependencies = [ "libc", "neli", "take-until", - "thiserror", + "thiserror 1.0.69", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +dependencies = [ + "bitflags 2.8.0", ] [[package]] @@ -2856,7 +3209,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" dependencies = [ "curve25519-dalek", - "rand_core", + "rand_core 0.6.4", "serde", "zeroize", ] @@ -2868,7 +3221,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", - "zerocopy-derive", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" +dependencies = [ + "zerocopy-derive 0.8.24", ] [[package]] @@ -2879,7 +3241,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.98", ] [[package]] @@ -2899,5 +3272,5 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.98", ] diff --git a/Cargo.toml b/Cargo.toml index d1f2c13b..9b94447d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,17 +2,17 @@ resolver = "2" members = [ - "rosenpass", - "cipher-traits", - "ciphers", - "util", - "constant-time", - "oqs", - "to", - "fuzz", - "secret-memory", - "rp", - "wireguard-broker", + "rosenpass", + "cipher-traits", + "ciphers", + "util", + "constant-time", + "oqs", + "to", + "fuzz", + "secret-memory", + "rp", + "wireguard-broker", ] default-members = ["rosenpass", "rp", "wireguard-broker"] @@ -42,39 +42,45 @@ toml = "0.7.8" static_assertions = "1.1.0" allocator-api2 = "0.2.14" memsec = { git = "https://github.com/rosenpass/memsec.git", rev = "aceb9baee8aec6844125bd6612f92e9a281373df", features = [ - "alloc_ext", + "alloc_ext", ] } rand = "0.8.5" typenum = "1.17.0" log = { version = "0.4.22" } clap = { version = "4.5.23", features = ["derive"] } -clap_mangen = "0.2.24" +clap_mangen = "0.2.29" clap_complete = "4.5.40" serde = { version = "1.0.217", features = ["derive"] } arbitrary = { version = "1.4.1", features = ["derive"] } anyhow = { version = "1.0.95", features = ["backtrace", "std"] } mio = { version = "1.0.3", features = ["net", "os-poll"] } oqs-sys = { version = "0.9.1", default-features = false, features = [ - 'classic_mceliece', - 'kyber', + 'classic_mceliece', + 'kyber', ] } blake2 = "0.10.6" +sha3 = "0.10.8" chacha20poly1305 = { version = "0.10.1", default-features = false, features = [ - "std", - "heapless", + "std", + "heapless", ] } zerocopy = { version = "0.7.35", features = ["derive"] } -home = "0.5.9" +home = "=0.5.9" # 5.11 requires rustc 1.81 derive_builder = "0.20.1" -tokio = { version = "1.42", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1.46", features = ["macros", "rt-multi-thread"] } postcard = { version = "1.1.1", features = ["alloc"] } libcrux = { version = "0.0.2-pre.2" } +libcrux-chacha20poly1305 = { version = "0.0.2-beta.3" } +libcrux-ml-kem = { version = "0.0.2-beta.3" } +libcrux-blake2 = { git = "https://github.com/cryspen/libcrux.git", rev = "10ce653e9476" } +libcrux-test-utils = { git = "https://github.com/cryspen/libcrux.git", rev = "0ab6d2dd9c1f" } hex-literal = { version = "0.4.1" } hex = { version = "0.4.3" } heck = { version = "0.5.0" } libc = { version = "0.2" } uds = { git = "https://github.com/rosenpass/uds" } signal-hook = "0.3.17" +lazy_static = "1.5" #Dev dependencies serial_test = "3.2.0" @@ -86,8 +92,10 @@ criterion = "0.5.1" allocator-api2-tests = "0.2.15" procspawn = { version = "1.0.1", features = ["test-support"] } - #Broker dependencies (might need cleanup or changes) wireguard-uapi = { version = "3.0.0", features = ["xplatform"] } command-fds = "0.2.3" rustix = { version = "0.38.42", features = ["net", "fs", "process"] } +futures = "0.3" +futures-util = "0.3" +x25519-dalek = "2" diff --git a/cipher-traits/Cargo.toml b/cipher-traits/Cargo.toml index 2e9ea32c..73a19b83 100644 --- a/cipher-traits/Cargo.toml +++ b/cipher-traits/Cargo.toml @@ -8,10 +8,13 @@ description = "Rosenpass internal traits for cryptographic primitives" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [dependencies] +thiserror = { workspace = true } +rosenpass-to = { workspace = true } [dev-dependencies] rosenpass-oqs = { workspace = true } rosenpass-secret-memory = { workspace = true } -anyhow = {workspace = true} +anyhow = { workspace = true } diff --git a/cipher-traits/src/algorithms.rs b/cipher-traits/src/algorithms.rs new file mode 100644 index 00000000..4ba989e4 --- /dev/null +++ b/cipher-traits/src/algorithms.rs @@ -0,0 +1,137 @@ +//! This module contains the traits for all the cryptographic algorithms used throughout Rosenpass. +//! These traits are marker traits that signal intent. They can also be used for trait objects. + +/// Constants and trait for the Incorrect HMAC over Blake2b, with 256 key and hash length. +pub mod keyed_hash_incorrect_hmac_blake2b { + use crate::primitives::keyed_hash::*; + + // These constants describe how they are used here, not what the algorithm defines. + + /// The key length used in [`KeyedHashIncorrectHmacBlake2b`]. + pub const KEY_LEN: usize = 32; + /// The hash length used in [`KeyedHashIncorrectHmacBlake2b`]. + pub const HASH_LEN: usize = 32; + + /// A [`KeyedHash`] that is an incorrect HMAC over Blake2 (a custom Rosenpass construction) + pub trait KeyedHashIncorrectHmacBlake2b: KeyedHash {} +} + +/// Constants and trait for Blake2b, with 256 key and hash length. +pub mod keyed_hash_blake2b { + use crate::primitives::keyed_hash::*; + + // These constants describe how they are used here, not what the algorithm defines. + + /// The key length used in [`KeyedHashBlake2b`]. + pub const KEY_LEN: usize = 32; + /// The hash length used in [`KeyedHashBlake2b`]. + pub const HASH_LEN: usize = 32; + + /// A [`KeyedHash`] that is Blake2b + pub trait KeyedHashBlake2b: KeyedHash {} +} + +/// Constants and trait for SHAKE256, with 256 key and hash length. +pub mod keyed_hash_shake256 { + use crate::primitives::keyed_hash::*; + + // These constants describe how they are used here, not what the algorithm defines. + + /// The key length used in [`KeyedHashShake256`]. + pub const KEY_LEN: usize = 32; + /// The hash length used in [`KeyedHashShake256`]. + pub const HASH_LEN: usize = 32; + + /// A [`KeyedHash`] that is SHAKE256. + pub trait KeyedHashShake256: KeyedHash {} +} + +/// Constants and trait for the ChaCha20Poly1305 AEAD +pub mod aead_chacha20poly1305 { + use crate::primitives::aead::*; + + // See https://datatracker.ietf.org/doc/html/rfc7539#section-2.8 + + /// The key length used in [`AeadChaCha20Poly1305`]. + pub const KEY_LEN: usize = 32; + /// The nonce length used in [`AeadChaCha20Poly1305`]. + pub const NONCE_LEN: usize = 12; + /// The tag length used in [`AeadChaCha20Poly1305`]. + pub const TAG_LEN: usize = 16; + + /// An [`Aead`] that is ChaCha20Poly1305. + pub trait AeadChaCha20Poly1305: Aead {} +} + +/// Constants and trait for the XChaCha20Poly1305 AEAD (i.e. ChaCha20Poly1305 with extended nonce +/// lengths) +pub mod aead_xchacha20poly1305 { + use crate::primitives::aead::*; + + // See https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha-03 + + /// The key length used in [`AeadXChaCha20Poly1305`]. + pub const KEY_LEN: usize = 32; + /// The nonce length used in [`AeadXChaCha20Poly1305`]. + pub const NONCE_LEN: usize = 24; + /// The tag length used in [`AeadXChaCha20Poly1305`]. + pub const TAG_LEN: usize = 16; + + /// An [`Aead`] that is XChaCha20Poly1305. + pub trait AeadXChaCha20Poly1305: Aead {} +} + +/// Constants and trait for the Kyber512 KEM +pub mod kem_kyber512 { + use crate::primitives::kem::*; + + // page 39 of https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.203.pdf + // (which is ml-kem instead of kyber, but it's the same) + + /// The secret key length used in [`KemKyber512`]. + pub const SK_LEN: usize = 1632; + + /// The public key length used in [`KemKyber512`]. + pub const PK_LEN: usize = 800; + + /// The ciphertext length used in [`KemKyber512`]. + pub const CT_LEN: usize = 768; + + /// The shared key length used in [`KemKyber512`]. + pub const SHK_LEN: usize = 32; + + /// A [`Kem`] that is Kyber512. + pub trait KemKyber512: Kem {} +} + +/// Constants and trait for the Classic McEliece 460896 KEM +pub mod kem_classic_mceliece460896 { + use crate::primitives::kem::*; + + // page 6 of https://classic.mceliece.org/mceliece-impl-20221023.pdf + + /// The secret key length used in [`KemClassicMceliece460896`]. + pub const SK_LEN: usize = 13608; + + /// The public key length used in [`KemClassicMceliece460896`]. + pub const PK_LEN: usize = 524160; + + /// The ciphertext length used in [`KemClassicMceliece460896`]. + pub const CT_LEN: usize = 156; + + /// The shared key length used in [`KemClassicMceliece460896`]. + pub const SHK_LEN: usize = 32; + + /// A [`Kem`] that is ClassicMceliece460896. + pub trait KemClassicMceliece460896: Kem {} +} + +pub use aead_chacha20poly1305::AeadChaCha20Poly1305; +pub use aead_xchacha20poly1305::AeadXChaCha20Poly1305; + +pub use kem_classic_mceliece460896::KemClassicMceliece460896; +pub use kem_kyber512::KemKyber512; + +pub use keyed_hash_blake2b::KeyedHashBlake2b; +pub use keyed_hash_incorrect_hmac_blake2b::KeyedHashIncorrectHmacBlake2b; +pub use keyed_hash_shake256::KeyedHashShake256; diff --git a/cipher-traits/src/lib.rs b/cipher-traits/src/lib.rs index 99369d9b..299e2a46 100644 --- a/cipher-traits/src/lib.rs +++ b/cipher-traits/src/lib.rs @@ -1,2 +1,5 @@ -mod kem; -pub use kem::Kem; +//! This trait contains traits, constants and wrappers that provid= the interface between Rosenpass +//! as a consumer of cryptographic libraries and the implementations of cryptographic algorithms. + +pub mod algorithms; +pub mod primitives; diff --git a/cipher-traits/src/primitives.rs b/cipher-traits/src/primitives.rs new file mode 100644 index 00000000..2e279fe6 --- /dev/null +++ b/cipher-traits/src/primitives.rs @@ -0,0 +1,10 @@ +//! Traits for cryptographic primitives used in Rosenpass, specifically KEM, AEAD and keyed +//! hashing. + +pub(crate) mod aead; +pub(crate) mod kem; +pub(crate) mod keyed_hash; + +pub use aead::{Aead, AeadWithNonceInCiphertext, Error as AeadError}; +pub use kem::{Error as KemError, Kem}; +pub use keyed_hash::*; diff --git a/cipher-traits/src/primitives/aead.rs b/cipher-traits/src/primitives/aead.rs new file mode 100644 index 00000000..06deea75 --- /dev/null +++ b/cipher-traits/src/primitives/aead.rs @@ -0,0 +1,175 @@ +use rosenpass_to::{ops::copy_slice, To as _}; +use thiserror::Error; + +/// Models authenticated encryption with assiciated data (AEAD) functionality. +/// +/// The methods of this trait take a `&self` argument as a receiver. This has two reasons: +/// 1. It makes type inference a lot smoother +/// 2. It allows to use the functionality through a trait object or having an enum that has +/// variants for multiple options (like e.g. the `KeyedHash` enum in `rosenpass-ciphers`). +/// +/// Since the caller needs an instance of the type to use the functionality, implementors are +/// adviced to implement the [`Default`] trait where possible. +/// +/// Example for encrypting a message with a specific [`Aead`] instance: +/// ``` +/// use rosenpass_cipher_traits::primitives::Aead; +/// +/// const KEY_LEN: usize = 32; +/// const NONCE_LEN: usize = 12; +/// const TAG_LEN: usize = 16; +/// +/// fn encrypt_message_given_an_aead( +/// aead: &AeadImpl, +/// msg: &str, +/// nonce: &[u8; NONCE_LEN], +/// encrypted: &mut [u8] +/// ) where AeadImpl: Aead { +/// let key = [0u8; KEY_LEN]; // This is not a secure key! +/// let ad = b""; // we don't need associated data here +/// aead.encrypt(encrypted, &key, nonce, ad, msg.as_bytes()).unwrap(); +/// } +/// ``` +/// +/// If only the type (but no instance) is available, then we can still encrypt, as long as the type +/// also is [`Default`]: +/// ``` +/// use rosenpass_cipher_traits::primitives::Aead; +/// +/// const KEY_LEN: usize = 32; +/// const NONCE_LEN: usize = 12; +/// const TAG_LEN: usize = 16; +/// +/// fn encrypt_message_without_aead( +/// msg: &str, +/// nonce: &[u8; NONCE_LEN], +/// encrypted: &mut [u8] +/// ) where AeadImpl: Default + Aead { +/// let key = [0u8; KEY_LEN]; // This is not a secure key! +/// let ad = b""; // we don't need associated data here +/// AeadImpl::default().encrypt(encrypted, &key, nonce, ad, msg.as_bytes()).unwrap(); +/// } +/// ``` +pub trait Aead { + const KEY_LEN: usize = KEY_LEN; + const NONCE_LEN: usize = NONCE_LEN; + const TAG_LEN: usize = TAG_LEN; + + /// Encrypts `plaintext` using the given `key` and `nonce`, taking into account the additional + /// data `ad` and writes the result into `ciphertext`. + /// + /// `ciphertext` must be exactly `TAG_LEN` longer than `plaintext`. + fn encrypt( + &self, + ciphertext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + plaintext: &[u8], + ) -> Result<(), Error>; + + /// Decrypts `ciphertexttext` using the given `key` and `nonce`, taking into account the additional + /// data `ad` and writes the result into `plaintext`. + /// + /// `ciphertext` must be exactly `TAG_LEN` longer than `plaintext`. + fn decrypt( + &self, + plaintext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + ciphertext: &[u8], + ) -> Result<(), Error>; +} + +/// Provides an AEAD API where the nonce is part of the ciphertext. +/// +/// The old xaead API had the ciphertext begin with the `nonce`. In order to not having to change +/// the calling code too much, we add a wrapper trait that provides this API and implement it for +/// all AEAD. +pub trait AeadWithNonceInCiphertext< + const KEY_LEN: usize, + const NONCE_LEN: usize, + const TAG_LEN: usize, +>: Aead +{ + /// Encrypts `plaintext` using the given `key` and `nonce`, taking into account the additional + /// data `ad` and writes the result into `ciphertext`. + /// + /// `ciphertext` must be exactly `TAG_LEN` + `NONCE_LEN` longer than `plaintext`. + fn encrypt_with_nonce_in_ctxt( + &self, + ciphertext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + plaintext: &[u8], + ) -> Result<(), Error> { + // The comparison looks complicated, but we need to do it this way to prevent + // over/underflows. + if ciphertext.len() < NONCE_LEN + TAG_LEN + || ciphertext.len() - TAG_LEN - NONCE_LEN < plaintext.len() + { + return Err(Error::InvalidLengths); + } + + let (n, rest) = ciphertext.split_at_mut(NONCE_LEN); + copy_slice(nonce).to(n); + + self.encrypt(rest, key, nonce, ad, plaintext) + } + + /// Decrypts `ciphertexttext` using the given `key` and `nonce`, taking into account the additional + /// data `ad` and writes the result into `plaintext`. + /// + /// `ciphertext` must be exactly `TAG_LEN` + `NONCE_LEN` longer than `plaintext`. + fn decrypt_with_nonce_in_ctxt( + &self, + plaintext: &mut [u8], + key: &[u8; KEY_LEN], + ad: &[u8], + ciphertext: &[u8], + ) -> Result<(), Error> { + // The comparison looks complicated, but we need to do it this way to prevent + // over/underflows. + if ciphertext.len() < NONCE_LEN + TAG_LEN + || ciphertext.len() - TAG_LEN - NONCE_LEN < plaintext.len() + { + return Err(Error::InvalidLengths); + } + + let (nonce, rest) = ciphertext.split_at(NONCE_LEN); + // We know this should be the right length (we just split it), and everything else would be + // very unexpected. + let nonce = nonce.try_into().map_err(|_| Error::InternalError)?; + + self.decrypt(plaintext, key, nonce, ad, rest) + } +} + +impl< + const KEY_LEN: usize, + const NONCE_LEN: usize, + const TAG_LEN: usize, + T: Aead, + > AeadWithNonceInCiphertext for T +{ +} + +/// The error returned by AEAD operations +#[derive(Debug, Error)] +pub enum Error { + /// An internal error occurred. This should never be happen and indicates an error in the + /// AEAD implementation. + #[error("internal error")] + InternalError, + + /// Could not decrypt a message because the message is not a valid ciphertext for the given + /// key. + #[error("decryption error")] + DecryptError, + + /// The provided buffers have the wrong lengths. + #[error("buffers have invalid length")] + InvalidLengths, +} diff --git a/cipher-traits/src/primitives/kem.rs b/cipher-traits/src/primitives/kem.rs new file mode 100644 index 00000000..4df959ec --- /dev/null +++ b/cipher-traits/src/primitives/kem.rs @@ -0,0 +1,212 @@ +//! Traits and implementations for Key Encapsulation Mechanisms (KEMs) +//! +//! KEMs are the interface provided by almost all post-quantum +//! secure key exchange mechanisms. +//! +//! Conceptually KEMs are akin to public-key encryption, but instead of encrypting +//! arbitrary data, KEMs are limited to the transmission of keys, randomly chosen during +//! encapsulation. +//! +//! The [Kem] Trait describes the basic API offered by a Key Encapsulation +//! Mechanism. Two implementations for it are provided: +//! [Kyber512](../../rosenpass_oqs/kyber_512/enum.Kyber512.html) and +//! [ClassicMceliece460896](../../rosenpass_oqs/classic_mceliece_460896/enum.ClassicMceliece460896.html). +//! +//! An example where Alice generates a keypair and gives her public key to Bob, for Bob to +//! encapsulate a symmetric key and Alice to decapsulate it would look as follows. +//! In the example, we are using Kyber512, but any KEM that correctly implements the [Kem] +//! trait could be used as well. +//!```rust +//! use rosenpass_cipher_traits::primitives::Kem; +//! use rosenpass_oqs::Kyber512; +//! # use rosenpass_secret_memory::{secret_policy_use_only_malloc_secrets, Secret}; +//! +//! type MyKem = Kyber512; +//! secret_policy_use_only_malloc_secrets(); +//! let mut alice_sk: Secret<{ MyKem::SK_LEN }> = Secret::zero(); +//! let mut alice_pk: [u8; MyKem::PK_LEN] = [0; MyKem::PK_LEN]; +//! MyKem::default().keygen(alice_sk.secret_mut(), &mut alice_pk)?; +//! +//! let mut bob_shk: Secret<{ MyKem::SHK_LEN }> = Secret::zero(); +//! let mut bob_ct: [u8; MyKem::CT_LEN] = [0; MyKem::CT_LEN]; +//! MyKem::default().encaps(bob_shk.secret_mut(), &mut bob_ct, &mut alice_pk)?; +//! +//! let mut alice_shk: Secret<{ MyKem::SHK_LEN }> = Secret::zero(); +//! MyKem::default().decaps(alice_shk.secret_mut(), alice_sk.secret_mut(), &mut bob_ct)?; +//! +//! # assert_eq!(alice_shk.secret(), bob_shk.secret()); +//! # Ok::<(), anyhow::Error>(()) +//!``` +//! +//! Implementing the [Kem]-trait for a KEM is easy. Mostly, you must format the KEM's +//! keys, and ciphertext as `u8` slices. Below, we provide an example for how the trait can +//! be implemented using a **HORRIBLY INSECURE** DummyKem that only uses static values for keys +//! and ciphertexts as an example. +//!```rust +//!# use rosenpass_cipher_traits::primitives::{Kem, KemError as Error}; +//! +//! struct DummyKem {} +//! impl Kem<1,1,1,1> for DummyKem { +//! +//! // For this DummyKem, we will use a single `u8` for everything +//! const SK_LEN: usize = 1; +//! const PK_LEN: usize = 1; +//! const CT_LEN: usize = 1; +//! const SHK_LEN: usize = 1; +//! +//! fn keygen(&self, sk: &mut [u8;1], pk: &mut [u8;1]) -> Result<(), Error> { +//! sk[0] = 42; +//! pk[0] = 21; +//! Ok(()) +//! } +//! +//! fn encaps(&self, shk: &mut [u8;1], ct: &mut [u8;1], pk: &[u8;1]) -> Result<(), Error> { +//! if pk[0] != 21 { +//! return Err(Error::InvalidArgument); +//! } +//! ct[0] = 7; +//! shk[0] = 17; +//! Ok(()) +//! } +//! +//! fn decaps(&self, shk: &mut [u8;1 ], sk: &[u8;1], ct: &[u8;1]) -> Result<(), Error> { +//! if sk[0] != 42 { +//! return Err(Error::InvalidArgument); +//! } +//! if ct[0] != 7 { +//! return Err(Error::InvalidArgument); +//! } +//! shk[0] = 17; +//! Ok(()) +//! } +//! } +//! +//! impl Default for DummyKem { +//! fn default() -> Self { +//! Self{} +//! } +//! } +//! # use rosenpass_secret_memory::{secret_policy_use_only_malloc_secrets, Secret}; +//! # +//! # type MyKem = DummyKem; +//! # secret_policy_use_only_malloc_secrets(); +//! # let mut alice_sk: Secret<{ MyKem::SK_LEN }> = Secret::zero(); +//! # let mut alice_pk: [u8; MyKem::PK_LEN] = [0; MyKem::PK_LEN]; +//! # MyKem::default().keygen(alice_sk.secret_mut(), &mut alice_pk)?; +//! +//! # let mut bob_shk: Secret<{ MyKem::SHK_LEN }> = Secret::zero(); +//! # let mut bob_ct: [u8; MyKem::CT_LEN] = [0; MyKem::CT_LEN]; +//! # MyKem::default().encaps(bob_shk.secret_mut(), &mut bob_ct, &mut alice_pk)?; +//! # +//! # let mut alice_shk: Secret<{ MyKem::SHK_LEN }> = Secret::zero(); +//! # MyKem::default().decaps(alice_shk.secret_mut(), alice_sk.secret_mut(), &mut bob_ct)?; +//! # +//! # assert_eq!(alice_shk.secret(), bob_shk.secret()); +//! # +//! # Ok::<(), Error>(()) +//!``` +//! + +use thiserror::Error; + +/// Key Encapsulation Mechanism +/// +/// The KEM interface defines three operations: Key generation, key encapsulation and key +/// decapsulation. The parameters are made available as associated constants for convenience. +/// +/// The methods of this trait take a `&self` argument as a receiver. This has two reasons: +/// 1. It makes type inference a lot smoother +/// 2. It allows to use the functionality through a trait object or having an enum that has +/// variants for multiple options (like e.g. the `KeyedHash` enum in `rosenpass-ciphers`). +/// +/// Since the caller needs an instance of the type to use the functionality, implementors are +/// adviced to implement the [`Default`] trait where possible. +/// +/// Example for encrypting a message with a specific [`Kem`] instance: +/// ``` +/// use rosenpass_cipher_traits::primitives::Kem; +/// +/// const SK_LEN: usize = 1632; +/// const PK_LEN: usize = 800; +/// const CT_LEN: usize = 768; +/// const SHK_LEN: usize = 32; +/// +/// fn encaps_given_a_kem( +/// kem: &KemImpl, +/// pk: &[u8; PK_LEN], +/// ct: &mut [u8; CT_LEN] +/// ) -> [u8; SHK_LEN] where KemImpl: Kem{ +/// let mut shk = [0u8; SHK_LEN]; +/// kem.encaps(&mut shk, ct, pk).unwrap(); +/// shk +/// } +/// ``` +/// +/// If only the type (but no instance) is available, then we can still use the trait, as long as +/// the type also is [`Default`]: +/// ``` +/// use rosenpass_cipher_traits::primitives::Kem; +/// +/// const SK_LEN: usize = 1632; +/// const PK_LEN: usize = 800; +/// const CT_LEN: usize = 768; +/// const SHK_LEN: usize = 32; +/// +/// fn encaps_without_kem( +/// pk: &[u8; PK_LEN], +/// ct: &mut [u8; CT_LEN] +/// ) -> [u8; SHK_LEN] +/// where KemImpl: Default + Kem { +/// let mut shk = [0u8; SHK_LEN]; +/// KemImpl::default().encaps(&mut shk, ct, pk).unwrap(); +/// shk +/// } +/// ``` +pub trait Kem { + /// The length of the secret (decapsulation) key. + const SK_LEN: usize = SK_LEN; + + /// The length of the public (encapsulation) key. + const PK_LEN: usize = PK_LEN; + + /// The length of the ciphertext. + const CT_LEN: usize = CT_LEN; + + /// The legnth of the resulting shared key. + const SHK_LEN: usize = SHK_LEN; + + /// Generate a keypair consisting of secret key (`sk`) and public key (`pk`) + /// + /// `keygen() -> sk, pk` + fn keygen(&self, sk: &mut [u8; SK_LEN], pk: &mut [u8; PK_LEN]) -> Result<(), Error>; + + /// From a public key (`pk`), generate a shared key (`shk`, for local use) + /// and a cipher text (`ct`, to be sent to the owner of the `pk`). + /// + /// `encaps(pk) -> shk, ct` + fn encaps( + &self, + shk: &mut [u8; SHK_LEN], + ct: &mut [u8; CT_LEN], + pk: &[u8; PK_LEN], + ) -> Result<(), Error>; + + /// From a secret key (`sk`) and a cipher text (`ct`) derive a shared key + /// (`shk`) + /// + /// `decaps(sk, ct) -> shk` + fn decaps( + &self, + shk: &mut [u8; SHK_LEN], + sk: &[u8; SK_LEN], + ct: &[u8; CT_LEN], + ) -> Result<(), Error>; +} + +#[derive(Debug, Error)] +pub enum Error { + #[error("invalid argument")] + InvalidArgument, + #[error("internal error")] + InternalError, +} diff --git a/cipher-traits/src/primitives/keyed_hash.rs b/cipher-traits/src/primitives/keyed_hash.rs new file mode 100644 index 00000000..93ecaf17 --- /dev/null +++ b/cipher-traits/src/primitives/keyed_hash.rs @@ -0,0 +1,159 @@ +use std::marker::PhantomData; + +/// Models a keyed hash function using an associated function (i.e. without `&self` receiver). +pub trait KeyedHash { + /// The error type used to signal what went wrong. + type Error; + + /// Performs a keyed hash using `key` and `data` and writes the output to `out` + fn keyed_hash( + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error>; +} + +/// Models a keyed hash function using a method (i.e. with a `&self` receiver). +/// +/// This makes type inference easier, but also requires having a [`KeyedHashInstance`] value, +/// instead of just the [`KeyedHash`] type. +pub trait KeyedHashInstance { + /// The error type used to signal what went wrong. + type Error; + + /// Performs a keyed hash using `key` and `data` and writes the output to `out` + fn keyed_hash( + &self, + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error>; +} + +/// This is a helper to allow for type parameter inference when calling functions +/// that need a [KeyedHash]. +/// +/// Really just binds the [KeyedHash] trait to a dummy variable, so the type of this dummy variable +/// can be used for type inference. Less typing work. +#[derive(Debug, PartialEq, Eq)] +pub struct InferKeyedHash +where + Static: KeyedHash, +{ + pub _phantom_keyed_hasher: PhantomData<*const Static>, +} + +impl InferKeyedHash +where + Static: KeyedHash, +{ + pub const KEY_LEN: usize = KEY_LEN; + pub const HASH_LEN: usize = HASH_LEN; + + pub const fn new() -> Self { + Self { + _phantom_keyed_hasher: PhantomData, + } + } + + /// This just forwards to [KeyedHash::keyed_hash] of the type parameter `Static` + fn keyed_hash_internal<'a>( + &self, + key: &'a [u8; KEY_LEN], + data: &'a [u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Static::Error> { + Static::keyed_hash(key, data, out) + } + + /// Returns the key length of the keyed hash function. + pub const fn key_len(self) -> usize { + Self::KEY_LEN + } + + /// Returns the hash length of the keyed hash function. + pub const fn hash_len(self) -> usize { + Self::HASH_LEN + } +} + +impl> + KeyedHashInstance for InferKeyedHash +{ + type Error = Static::Error; + + fn keyed_hash( + &self, + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Static::Error> { + self.keyed_hash_internal(key, data, out) + } +} + +// Helper traits ///////////////////////////////////////////// + +impl Default + for InferKeyedHash +where + Static: KeyedHash, +{ + fn default() -> Self { + Self::new() + } +} + +impl Clone + for InferKeyedHash +where + Static: KeyedHash, +{ + fn clone(&self) -> Self { + *self + } +} + +impl Copy + for InferKeyedHash +where + Static: KeyedHash, +{ +} + +use rosenpass_to::{with_destination, To}; + +/// Extends the [`KeyedHash`] trait with a [`To`]-flavoured function. +pub trait KeyedHashTo: + KeyedHash +{ + fn keyed_hash_to( + key: &[u8; KEY_LEN], + data: &[u8], + ) -> impl To<[u8; HASH_LEN], Result<(), Self::Error>> { + with_destination(|out| Self::keyed_hash(key, data, out)) + } +} + +impl> + KeyedHashTo for T +{ +} + +/// Extends the [`KeyedHashInstance`] trait with a [`To`]-flavoured function. +pub trait KeyedHashInstanceTo: + KeyedHashInstance +{ + fn keyed_hash_to( + &self, + key: &[u8; KEY_LEN], + data: &[u8], + ) -> impl To<[u8; HASH_LEN], Result<(), Self::Error>> { + with_destination(|out| self.keyed_hash(key, data, out)) + } +} + +impl> + KeyedHashInstanceTo for T +{ +} diff --git a/ciphers/Cargo.toml b/ciphers/Cargo.toml index 9e5312d3..7931f477 100644 --- a/ciphers/Cargo.toml +++ b/ciphers/Cargo.toml @@ -8,9 +8,42 @@ description = "Rosenpass internal ciphers and other cryptographic primitives use homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [features] -experiment_libcrux = ["dep:libcrux"] +# whether the types should be defined +experiment_libcrux_define_blake2 = ["dep:libcrux-blake2", "dep:thiserror"] +experiment_libcrux_define_kyber = ["dep:libcrux-ml-kem", "dep:rand"] +experiment_libcrux_define_chachapoly = ["dep:libcrux-chacha20poly1305"] + +# whether the types should be used by default +experiment_libcrux_blake2 = ["experiment_libcrux_define_blake2"] +experiment_libcrux_kyber = ["experiment_libcrux_define_kyber"] +experiment_libcrux_chachapoly = ["experiment_libcrux_define_chachapoly"] +experiment_libcrux_chachapoly_test = [ + "experiment_libcrux_define_chachapoly", + "dep:libcrux", +] + +# shorthands +experiment_libcrux_define_all = [ + "experiment_libcrux_define_blake2", + "experiment_libcrux_define_chachapoly", + "experiment_libcrux_define_kyber", +] +experiment_libcrux_all = [ + "experiment_libcrux_blake2", + "experiment_libcrux_chachapoly", + "experiment_libcrux_chachapoly_test", + "experiment_libcrux_kyber", +] + +bench = ["experiment_libcrux_define_all"] + +[[bench]] +name = "primitives" +harness = false +required-features = ["bench"] [dependencies] anyhow = { workspace = true } @@ -19,8 +52,22 @@ rosenpass-constant-time = { workspace = true } rosenpass-secret-memory = { workspace = true } rosenpass-oqs = { workspace = true } rosenpass-util = { workspace = true } +rosenpass-cipher-traits = { workspace = true } static_assertions = { workspace = true } zeroize = { workspace = true } chacha20poly1305 = { workspace = true } blake2 = { workspace = true } +sha3 = { workspace = true } +rand = { workspace = true, optional = true } +thiserror = { workspace = true, optional = true } + +libcrux-chacha20poly1305 = { workspace = true, optional = true } +libcrux-blake2 = { workspace = true, optional = true } +libcrux-ml-kem = { workspace = true, optional = true, features = ["kyber"] } + +# this one is only used in testing, so it requires the `experiment_libcrux_chachapoly_test` feature. libcrux = { workspace = true, optional = true } + +[dev-dependencies] +rand = { workspace = true } +criterion = { workspace = true } diff --git a/ciphers/benches/primitives.rs b/ciphers/benches/primitives.rs new file mode 100644 index 00000000..f1ef4d7e --- /dev/null +++ b/ciphers/benches/primitives.rs @@ -0,0 +1,378 @@ +criterion::criterion_main!(keyed_hash::benches, aead::benches, kem::benches); + +fn benchid(base: KvPairs, last: KvPairs) -> String { + format!("{base},{last}") +} + +#[derive(Clone, Copy, Debug)] +struct KvPair<'a>(&'a str, &'a str); + +impl std::fmt::Display for KvPair<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{k}={v}", k = self.0, v = self.1) + } +} + +#[derive(Clone, Copy, Debug)] +struct KvPairs<'a>(&'a [KvPair<'a>]); + +impl std::fmt::Display for KvPairs<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.0.len() { + 0 => Ok(()), + 1 => write!(f, "{}", &self.0[0]), + _ => { + let mut delim = ""; + for pair in self.0 { + write!(f, "{delim}{pair}")?; + delim = ","; + } + Ok(()) + } + } + } +} + +mod kem { + criterion::criterion_group!( + benches, + bench_kyber512_libcrux, + bench_kyber512_oqs, + bench_classicmceliece460896_oqs + ); + + use criterion::Criterion; + + fn bench_classicmceliece460896_oqs(c: &mut Criterion) { + template( + c, + "classicmceliece460896", + "oqs", + rosenpass_oqs::ClassicMceliece460896, + ); + } + + fn bench_kyber512_libcrux(c: &mut Criterion) { + template( + c, + "kyber512", + "libcrux", + rosenpass_ciphers::subtle::libcrux::kyber512::Kyber512, + ); + } + + fn bench_kyber512_oqs(c: &mut Criterion) { + template(c, "kyber512", "oqs", rosenpass_oqs::Kyber512); + } + + use rosenpass_cipher_traits::primitives::Kem; + + fn template< + const SK_LEN: usize, + const PK_LEN: usize, + const CT_LEN: usize, + const SHK_LEN: usize, + T: Kem, + >( + c: &mut Criterion, + alg_name: &str, + impl_name: &str, + scheme: T, + ) { + use super::{benchid, KvPair, KvPairs}; + + let base = [ + KvPair("primitive", "kem"), + KvPair("algorithm", alg_name), + KvPair("implementation", impl_name), + KvPair("length", "-1"), + ]; + + let kem_benchid = |op| benchid(KvPairs(&base), KvPairs(&[KvPair("operation", op)])); + + c.bench_function(&kem_benchid("keygen"), |bench| { + let mut sk = [0; SK_LEN]; + let mut pk = [0; PK_LEN]; + + bench.iter(|| { + scheme.keygen(&mut sk, &mut pk).unwrap(); + }); + }); + + c.bench_function(&kem_benchid("encaps"), |bench| { + let mut sk = [0; SK_LEN]; + let mut pk = [0; PK_LEN]; + let mut ct = [0; CT_LEN]; + let mut shk = [0; SHK_LEN]; + + scheme.keygen(&mut sk, &mut pk).unwrap(); + + bench.iter(|| { + scheme.encaps(&mut shk, &mut ct, &pk).unwrap(); + }); + }); + + c.bench_function(&kem_benchid("decaps"), |bench| { + let mut sk = [0; SK_LEN]; + let mut pk = [0; PK_LEN]; + let mut ct = [0; CT_LEN]; + let mut shk = [0; SHK_LEN]; + let mut shk2 = [0; SHK_LEN]; + + scheme.keygen(&mut sk, &mut pk).unwrap(); + scheme.encaps(&mut shk, &mut ct, &pk).unwrap(); + + bench.iter(|| { + scheme.decaps(&mut shk2, &sk, &ct).unwrap(); + }); + }); + } +} +mod aead { + criterion::criterion_group!( + benches, + bench_chachapoly_libcrux, + bench_chachapoly_rustcrypto, + bench_xchachapoly_rustcrypto, + ); + + use criterion::Criterion; + + const KEY_LEN: usize = rosenpass_ciphers::Aead::KEY_LEN; + const TAG_LEN: usize = rosenpass_ciphers::Aead::TAG_LEN; + + fn bench_xchachapoly_rustcrypto(c: &mut Criterion) { + template( + c, + "xchacha20poly1305", + "rustcrypto", + rosenpass_ciphers::subtle::rust_crypto::xchacha20poly1305_ietf::XChaCha20Poly1305, + ); + } + + fn bench_chachapoly_rustcrypto(c: &mut Criterion) { + template( + c, + "chacha20poly1305", + "rustcrypto", + rosenpass_ciphers::subtle::rust_crypto::chacha20poly1305_ietf::ChaCha20Poly1305, + ); + } + + fn bench_chachapoly_libcrux(c: &mut Criterion) { + template( + c, + "chacha20poly1305", + "libcrux", + rosenpass_ciphers::subtle::libcrux::chacha20poly1305_ietf::ChaCha20Poly1305, + ); + } + + use rosenpass_cipher_traits::primitives::Aead; + + fn template>( + c: &mut Criterion, + alg_name: &str, + impl_name: &str, + scheme: T, + ) { + use crate::{benchid, KvPair, KvPairs}; + + let base = [ + KvPair("primitive", "aead"), + KvPair("algorithm", alg_name), + KvPair("implementation", impl_name), + ]; + let aead_benchid = |op, len| { + benchid( + KvPairs(&base), + KvPairs(&[KvPair("operation", op), KvPair("length", len)]), + ) + }; + + let key = [12; KEY_LEN]; + let nonce = [23; NONCE_LEN]; + let ad = []; + + c.bench_function(&aead_benchid("encrypt", "0byte"), |bench| { + const DATA_LEN: usize = 0; + + let ptxt = []; + let mut ctxt = [0; DATA_LEN + TAG_LEN]; + + bench.iter(|| { + scheme.encrypt(&mut ctxt, &key, &nonce, &ad, &ptxt).unwrap(); + }); + }); + + c.bench_function(&aead_benchid("decrypt", "0byte"), |bench| { + const DATA_LEN: usize = 0; + + let ptxt = []; + let mut ctxt = [0; DATA_LEN + TAG_LEN]; + let mut ptxt_out = [0u8; DATA_LEN]; + + scheme.encrypt(&mut ctxt, &key, &nonce, &ad, &ptxt).unwrap(); + + bench.iter(|| { + scheme + .decrypt(&mut ptxt_out, &key, &nonce, &ad, &mut ctxt) + .unwrap() + }) + }); + + c.bench_function(&aead_benchid("encrypt", "32byte"), |bench| { + const DATA_LEN: usize = 32; + + let ptxt = [34u8; DATA_LEN]; + let mut ctxt = [0; DATA_LEN + TAG_LEN]; + + bench.iter(|| { + scheme.encrypt(&mut ctxt, &key, &nonce, &ad, &ptxt).unwrap(); + }); + }); + + c.bench_function(&aead_benchid("decrypt", "32byte"), |bench| { + const DATA_LEN: usize = 32; + + let ptxt = [34u8; DATA_LEN]; + let mut ctxt = [0; DATA_LEN + TAG_LEN]; + let mut ptxt_out = [0u8; DATA_LEN]; + + scheme.encrypt(&mut ctxt, &key, &nonce, &ad, &ptxt).unwrap(); + + bench.iter(|| { + scheme + .decrypt(&mut ptxt_out, &key, &nonce, &ad, &mut ctxt) + .unwrap() + }) + }); + + c.bench_function(&aead_benchid("encrypt", "1024byte"), |bench| { + const DATA_LEN: usize = 1024; + + let ptxt = [34u8; DATA_LEN]; + let mut ctxt = [0; DATA_LEN + TAG_LEN]; + + bench.iter(|| { + scheme.encrypt(&mut ctxt, &key, &nonce, &ad, &ptxt).unwrap(); + }); + }); + c.bench_function(&aead_benchid("decrypt", "1024byte"), |bench| { + const DATA_LEN: usize = 1024; + + let ptxt = [34u8; DATA_LEN]; + let mut ctxt = [0; DATA_LEN + TAG_LEN]; + let mut ptxt_out = [0u8; DATA_LEN]; + + scheme.encrypt(&mut ctxt, &key, &nonce, &ad, &ptxt).unwrap(); + + bench.iter(|| { + scheme + .decrypt(&mut ptxt_out, &key, &nonce, &ad, &mut ctxt) + .unwrap() + }) + }); + } +} + +mod keyed_hash { + criterion::criterion_group!( + benches, + bench_blake2b_rustcrypto, + bench_blake2b_libcrux, + bench_shake256_rustcrypto, + ); + + const KEY_LEN: usize = 32; + const HASH_LEN: usize = 32; + + use criterion::Criterion; + + fn bench_shake256_rustcrypto(c: &mut Criterion) { + template( + c, + "shake256", + "rustcrypto", + &rosenpass_ciphers::subtle::rust_crypto::keyed_shake256::SHAKE256Core, + ); + } + + fn bench_blake2b_rustcrypto(c: &mut Criterion) { + template( + c, + "blake2b", + "rustcrypto", + &rosenpass_ciphers::subtle::rust_crypto::blake2b::Blake2b, + ); + } + + fn bench_blake2b_libcrux(c: &mut Criterion) { + template( + c, + "blake2b", + "libcrux", + &rosenpass_ciphers::subtle::libcrux::blake2b::Blake2b, + ); + } + + use rosenpass_cipher_traits::primitives::KeyedHash; + + fn template>( + c: &mut Criterion, + alg_name: &str, + impl_name: &str, + _: &H, + ) where + H::Error: std::fmt::Debug, + { + use crate::{benchid, KvPair, KvPairs}; + + let key = [12u8; KEY_LEN]; + let mut out = [0u8; HASH_LEN]; + + let base = [ + KvPair("primitive", "keyedhash"), + KvPair("algorithm", alg_name), + KvPair("implementation", impl_name), + KvPair("operation", "hash"), + ]; + let keyedhash_benchid = |len| benchid(KvPairs(&base), KvPairs(&[KvPair("length", len)])); + + c.bench_function(&keyedhash_benchid("0byte"), |bench| { + let bytes = []; + + bench.iter(|| { + H::keyed_hash(&key, &bytes, &mut out).unwrap(); + }) + }) + .bench_function(&keyedhash_benchid("32byte"), |bench| { + let bytes = [34u8; 32]; + + bench.iter(|| { + H::keyed_hash(&key, &bytes, &mut out).unwrap(); + }) + }) + .bench_function(&keyedhash_benchid("64byte"), |bench| { + let bytes = [34u8; 64]; + + bench.iter(|| { + H::keyed_hash(&key, &bytes, &mut out).unwrap(); + }) + }) + .bench_function(&keyedhash_benchid("128byte"), |bench| { + let bytes = [34u8; 128]; + + bench.iter(|| { + H::keyed_hash(&key, &bytes, &mut out).unwrap(); + }) + }) + .bench_function(&keyedhash_benchid("1024byte"), |bench| { + let bytes = [34u8; 1024]; + + bench.iter(|| { + H::keyed_hash(&key, &bytes, &mut out).unwrap(); + }) + }); + } +} diff --git a/ciphers/src/hash_domain.rs b/ciphers/src/hash_domain.rs index 2f674600..ad11a4bc 100644 --- a/ciphers/src/hash_domain.rs +++ b/ciphers/src/hash_domain.rs @@ -1,74 +1,75 @@ +//! +//!```rust +//! # use rosenpass_ciphers::hash_domain::{HashDomain, HashDomainNamespace, SecretHashDomain, SecretHashDomainNamespace}; +//! use rosenpass_ciphers::KeyedHash; +//! use rosenpass_secret_memory::Secret; +//! # rosenpass_secret_memory::secret_policy_use_only_malloc_secrets(); +//! +//! const PROTOCOL_IDENTIFIER: &str = "MY_PROTOCOL:IDENTIFIER"; +//! // create use once hash domain for the protocol identifier +//! let mut hash_domain = HashDomain::zero(KeyedHash::keyed_shake256()); +//! hash_domain = hash_domain.mix(PROTOCOL_IDENTIFIER.as_bytes())?; +//! // upgrade to reusable hash domain +//! let hash_domain_namespace: HashDomainNamespace = hash_domain.dup(); +//! // derive new key +//! let key_identifier = "my_key_identifier"; +//! let key = hash_domain_namespace.mix(key_identifier.as_bytes())?.into_value(); +//! // derive a new key based on a secret +//! const MY_SECRET_LEN: usize = 21; +//! let my_secret_bytes = "my super duper secret".as_bytes(); +//! let my_secret: Secret<21> = Secret::from_slice("my super duper secret".as_bytes()); +//! let secret_hash_domain: SecretHashDomain = hash_domain_namespace.mix_secret(my_secret)?; +//! // derive a new key based on the secret key +//! let new_key_identifier = "my_new_key_identifier".as_bytes(); +//! let new_key = secret_hash_domain.mix(new_key_identifier)?.into_secret(); +//! +//! # Ok::<(), anyhow::Error>(()) +//!``` +//! + use anyhow::Result; use rosenpass_secret_memory::Secret; -use rosenpass_to::To; +use rosenpass_to::To as _; -use crate::keyed_hash as hash; +pub use crate::{KeyedHash, KEY_LEN}; -pub use hash::KEY_LEN; - -/// -///```rust -/// # use rosenpass_ciphers::hash_domain::{HashDomain, HashDomainNamespace, SecretHashDomain, SecretHashDomainNamespace}; -/// use rosenpass_secret_memory::Secret; -/// # rosenpass_secret_memory::secret_policy_use_only_malloc_secrets(); -/// -/// const PROTOCOL_IDENTIFIER: &str = "MY_PROTOCOL:IDENTIFIER"; -/// // create use once hash domain for the protocol identifier -/// let mut hash_domain = HashDomain::zero(); -/// hash_domain = hash_domain.mix(PROTOCOL_IDENTIFIER.as_bytes())?; -/// // upgrade to reusable hash domain -/// let hash_domain_namespace: HashDomainNamespace = hash_domain.dup(); -/// // derive new key -/// let key_identifier = "my_key_identifier"; -/// let key = hash_domain_namespace.mix(key_identifier.as_bytes())?.into_value(); -/// // derive a new key based on a secret -/// const MY_SECRET_LEN: usize = 21; -/// let my_secret_bytes = "my super duper secret".as_bytes(); -/// let my_secret: Secret<21> = Secret::from_slice("my super duper secret".as_bytes()); -/// let secret_hash_domain: SecretHashDomain = hash_domain_namespace.mix_secret(my_secret)?; -/// // derive a new key based on the secret key -/// let new_key_identifier = "my_new_key_identifier".as_bytes(); -/// let new_key = secret_hash_domain.mix(new_key_identifier)?.into_secret(); -/// -/// # Ok::<(), anyhow::Error>(()) -///``` -/// +use rosenpass_cipher_traits::primitives::KeyedHashInstanceTo; // TODO Use a proper Dec interface /// A use-once hash domain for a specified key that can be used directly. /// The key must consist of [KEY_LEN] many bytes. If the key must remain secret, /// use [SecretHashDomain] instead. #[derive(Clone, Debug)] -pub struct HashDomain([u8; KEY_LEN]); +pub struct HashDomain([u8; KEY_LEN], KeyedHash); /// A reusable hash domain for a namespace identified by the key. /// The key must consist of [KEY_LEN] many bytes. If the key must remain secret, /// use [SecretHashDomainNamespace] instead. #[derive(Clone, Debug)] -pub struct HashDomainNamespace([u8; KEY_LEN]); +pub struct HashDomainNamespace([u8; KEY_LEN], KeyedHash); /// A use-once hash domain for a specified key that can be used directly /// by wrapping it in [Secret]. The key must consist of [KEY_LEN] many bytes. #[derive(Clone, Debug)] -pub struct SecretHashDomain(Secret); +pub struct SecretHashDomain(Secret, KeyedHash); /// A reusable secure hash domain for a namespace identified by the key and that keeps the key secure /// by wrapping it in [Secret]. The key must consist of [KEY_LEN] many bytes. #[derive(Clone, Debug)] -pub struct SecretHashDomainNamespace(Secret); +pub struct SecretHashDomainNamespace(Secret, KeyedHash); impl HashDomain { /// Creates a nw [HashDomain] initialized with a all-zeros key. - pub fn zero() -> Self { - Self([0u8; KEY_LEN]) + pub fn zero(choice: KeyedHash) -> Self { + Self([0u8; KEY_LEN], choice) } /// Turns this [HashDomain] into a [HashDomainNamespace], keeping the key. pub fn dup(self) -> HashDomainNamespace { - HashDomainNamespace(self.0) + HashDomainNamespace(self.0, self.1) } /// Turns this [HashDomain] into a [SecretHashDomain] by wrapping the key into a [Secret] /// and creating a new [SecretHashDomain] from it. pub fn turn_secret(self) -> SecretHashDomain { - SecretHashDomain(Secret::from_slice(&self.0)) + SecretHashDomain(Secret::from_slice(&self.0), self.1) } // TODO: Protocol! Use domain separation to ensure that @@ -77,14 +78,43 @@ impl HashDomain { /// as the `data` and uses the result as the key for the new [HashDomain]. /// pub fn mix(self, v: &[u8]) -> Result { - Ok(Self(hash::hash(&self.0, v).collect::<[u8; KEY_LEN]>()?)) + let mut new_key: [u8; KEY_LEN] = [0u8; KEY_LEN]; + self.1.keyed_hash_to(&self.0, v).to(&mut new_key)?; + Ok(Self(new_key, self.1)) + } + + /// Version of [Self::mix] that accepts an iterator and mixes all values from the iterator into + /// this hash domain. + /// + /// # Examples + /// + /// ```rust + /// use rosenpass_ciphers::{hash_domain::HashDomain, KeyedHash}; + /// + /// let hasher = HashDomain::zero(KeyedHash::keyed_shake256()); + /// assert_eq!( + /// hasher.clone().mix(b"Hello")?.mix(b"World")?.into_value(), + /// hasher.clone().mix_many([b"Hello", b"World"])?.into_value() + /// ); + /// + /// Ok::<(), anyhow::Error>(()) + /// ``` + pub fn mix_many(mut self, it: I) -> Result + where + I: IntoIterator, + T: AsRef<[u8]>, + { + for e in it { + self = self.mix(e.as_ref())?; + } + Ok(self) } /// Creates a new [SecretHashDomain] by mixing in a new key `v` /// by calling [SecretHashDomain::invoke_primitive] with this /// [HashDomain]'s key as `k` and `v` as `d`. pub fn mix_secret(self, v: Secret) -> Result { - SecretHashDomain::invoke_primitive(&self.0, v.secret()) + SecretHashDomain::invoke_primitive(&self.0, v.secret(), self.1) } /// Gets the key of this [HashDomain]. @@ -98,9 +128,9 @@ impl HashDomainNamespace { /// it evaluates [hash::hash] with the key of this HashDomainNamespace key as the key and `v` /// as the `data` and uses the result as the key for the new [HashDomain]. pub fn mix(&self, v: &[u8]) -> Result { - Ok(HashDomain( - hash::hash(&self.0, v).collect::<[u8; KEY_LEN]>()?, - )) + let mut new_key: [u8; KEY_LEN] = [0u8; KEY_LEN]; + self.1.keyed_hash_to(&self.0, v).to(&mut new_key)?; + Ok(HashDomain(new_key, self.1.clone())) } /// Creates a new [SecretHashDomain] by mixing in a new key `v` @@ -109,7 +139,7 @@ impl HashDomainNamespace { /// /// It requires that `v` consists of exactly [KEY_LEN] many bytes. pub fn mix_secret(&self, v: Secret) -> Result { - SecretHashDomain::invoke_primitive(&self.0, v.secret()) + SecretHashDomain::invoke_primitive(&self.0, v.secret(), self.1.clone()) } } @@ -118,27 +148,35 @@ impl SecretHashDomain { /// [hash::hash] with `k` as the `key` and `d` s the `data`, and using the result /// as the content for the new [SecretHashDomain]. /// Both `k` and `d` have to be exactly [KEY_LEN] bytes in length. - pub fn invoke_primitive(k: &[u8], d: &[u8]) -> Result { - let mut r = SecretHashDomain(Secret::zero()); - hash::hash(k, d).to(r.0.secret_mut())?; + /// TODO: docu + pub fn invoke_primitive( + k: &[u8], + d: &[u8], + hash_choice: KeyedHash, + ) -> Result { + let mut new_secret_key = Secret::zero(); + hash_choice + .keyed_hash_to(k.try_into()?, d) + .to(new_secret_key.secret_mut())?; + let r = SecretHashDomain(new_secret_key, hash_choice); Ok(r) } /// Creates a new [SecretHashDomain] that is initialized with an all zeros key. - pub fn zero() -> Self { - Self(Secret::zero()) + pub fn zero(hash_choice: KeyedHash) -> Self { + Self(Secret::zero(), hash_choice) } /// Turns this [SecretHashDomain] into a [SecretHashDomainNamespace]. pub fn dup(self) -> SecretHashDomainNamespace { - SecretHashDomainNamespace(self.0) + SecretHashDomainNamespace(self.0, self.1) } /// Creates a new [SecretHashDomain] from a [Secret] `k`. /// /// It requires that `k` consist of exactly [KEY_LEN] bytes. - pub fn danger_from_secret(k: Secret) -> Self { - Self(k) + pub fn danger_from_secret(k: Secret, hash_choice: KeyedHash) -> Self { + Self(k, hash_choice) } /// Creates a new [SecretHashDomain] by mixing in a new key `v`. Specifically, @@ -147,7 +185,47 @@ impl SecretHashDomain { /// /// It requires that `v` consists of exactly [KEY_LEN] many bytes. pub fn mix(self, v: &[u8]) -> Result { - Self::invoke_primitive(self.0.secret(), v) + Self::invoke_primitive(self.0.secret(), v, self.1) + } + + /// Version of [Self::mix] that accepts an iterator and mixes all values from the iterator into + /// this hash domain. + /// + /// # Examples + /// + /// ```rust + /// use rosenpass_ciphers::{hash_domain::HashDomain, KeyedHash}; + /// + /// rosenpass_secret_memory::secret_policy_use_only_malloc_secrets(); + /// + /// let hasher = HashDomain::zero(KeyedHash::keyed_shake256()); + /// assert_eq!( + /// hasher + /// .clone() + /// .turn_secret() + /// .mix(b"Hello")? + /// .mix(b"World")? + /// .into_secret() + /// .secret(), + /// hasher + /// .clone() + /// .turn_secret() + /// .mix_many([b"Hello", b"World"])? + /// .into_secret() + /// .secret(), + /// ); + + /// Ok::<(), anyhow::Error>(()) + /// ``` + pub fn mix_many(mut self, it: I) -> Result + where + I: IntoIterator, + T: AsRef<[u8]>, + { + for e in it { + self = self.mix(e.as_ref())?; + } + Ok(self) } /// Creates a new [SecretHashDomain] by mixing in a new key `v` @@ -156,21 +234,13 @@ impl SecretHashDomain { /// /// It requires that `v` consists of exactly [KEY_LEN] many bytes. pub fn mix_secret(self, v: Secret) -> Result { - Self::invoke_primitive(self.0.secret(), v.secret()) + Self::invoke_primitive(self.0.secret(), v.secret(), self.1) } /// Get the secret key data from this [SecretHashDomain]. pub fn into_secret(self) -> Secret { self.0 } - - /// Evaluate [hash::hash] with this [SecretHashDomain]'s data as the `key` and - /// `dst` as the `data` and stores the result as the new data for this [SecretHashDomain]. - /// - /// It requires that both `v` and `d` consist of exactly [KEY_LEN] many bytes. - pub fn into_secret_slice(mut self, v: &[u8], dst: &[u8]) -> Result<()> { - hash::hash(v, dst).to(self.0.secret_mut()) - } } impl SecretHashDomainNamespace { @@ -180,7 +250,7 @@ impl SecretHashDomainNamespace { /// /// It requires that `v` consists of exactly [KEY_LEN] many bytes. pub fn mix(&self, v: &[u8]) -> Result { - SecretHashDomain::invoke_primitive(self.0.secret(), v) + SecretHashDomain::invoke_primitive(self.0.secret(), v, self.1.clone()) } /// Creates a new [SecretHashDomain] by mixing in a new key `v` @@ -189,7 +259,7 @@ impl SecretHashDomainNamespace { /// /// It requires that `v` consists of exactly [KEY_LEN] many bytes. pub fn mix_secret(&self, v: Secret) -> Result { - SecretHashDomain::invoke_primitive(self.0.secret(), v.secret()) + SecretHashDomain::invoke_primitive(self.0.secret(), v.secret(), self.1.clone()) } // TODO: This entire API is not very nice; we need this for biscuits, but @@ -199,4 +269,8 @@ impl SecretHashDomainNamespace { pub fn danger_into_secret(self) -> Secret { self.0 } + + pub fn keyed_hash(&self) -> &KeyedHash { + &self.1 + } } diff --git a/ciphers/src/lib.rs b/ciphers/src/lib.rs index 6b6c67fb..392f0f4e 100644 --- a/ciphers/src/lib.rs +++ b/ciphers/src/lib.rs @@ -1,11 +1,12 @@ +use rosenpass_cipher_traits::primitives::Aead as AeadTrait; use static_assertions::const_assert; pub mod subtle; /// All keyed primitives in this crate use 32 byte keys pub const KEY_LEN: usize = 32; -const_assert!(KEY_LEN == aead::KEY_LEN); -const_assert!(KEY_LEN == xaead::KEY_LEN); +const_assert!(KEY_LEN == Aead::KEY_LEN); +const_assert!(KEY_LEN == XAead::KEY_LEN); const_assert!(KEY_LEN == hash_domain::KEY_LEN); /// Keyed hashing @@ -13,41 +14,33 @@ const_assert!(KEY_LEN == hash_domain::KEY_LEN); /// This should only be used for implementation details; anything with relevance /// to the cryptographic protocol should use the facilities in [hash_domain], (though /// hash domain uses this module internally) -pub mod keyed_hash { - pub use crate::subtle::incorrect_hmac_blake2b::{ - hash, KEY_LEN, KEY_MAX, KEY_MIN, OUT_MAX, OUT_MIN, - }; -} +pub use crate::subtle::keyed_hash::KeyedHash; -/// Authenticated encryption with associated data +/// Authenticated encryption with associated data (AEAD) /// Chacha20poly1305 is used. -pub mod aead { - #[cfg(not(feature = "experiment_libcrux"))] - pub use crate::subtle::chacha20poly1305_ietf::{decrypt, encrypt, KEY_LEN, NONCE_LEN, TAG_LEN}; - #[cfg(feature = "experiment_libcrux")] - pub use crate::subtle::chacha20poly1305_ietf_libcrux::{ - decrypt, encrypt, KEY_LEN, NONCE_LEN, TAG_LEN, - }; -} +#[cfg(feature = "experiment_libcrux_chachapoly")] +pub use subtle::libcrux::chacha20poly1305_ietf::ChaCha20Poly1305 as Aead; -/// Authenticated encryption with associated data with a constant nonce +/// Authenticated encryption with associated data (AEAD) +/// Chacha20poly1305 is used. +#[cfg(not(feature = "experiment_libcrux_chachapoly"))] +pub use crate::subtle::rust_crypto::chacha20poly1305_ietf::ChaCha20Poly1305 as Aead; + +/// Authenticated encryption with associated data with a extended-length nonce (XAEAD) /// XChacha20poly1305 is used. -pub mod xaead { - pub use crate::subtle::xchacha20poly1305_ietf::{ - decrypt, encrypt, KEY_LEN, NONCE_LEN, TAG_LEN, - }; -} +pub use crate::subtle::rust_crypto::xchacha20poly1305_ietf::XChaCha20Poly1305 as XAead; + +/// Use Classic-McEcliece-460986 as the Static KEM. +/// +/// See [rosenpass_oqs::ClassicMceliece460896] for more details. +pub use rosenpass_oqs::ClassicMceliece460896 as StaticKem; + +/// Use Kyber-512 as the Static KEM +/// +/// See [rosenpass_oqs::Kyber512] for more details. +#[cfg(not(feature = "experiment_libcrux_kyber"))] +pub use rosenpass_oqs::Kyber512 as EphemeralKem; +#[cfg(feature = "experiment_libcrux_kyber")] +pub use subtle::libcrux::kyber512::Kyber512 as EphemeralKem; pub mod hash_domain; - -/// This crate includes two key encapsulation mechanisms. -/// Namely ClassicMceliece460896 (also referred to as `StaticKem` sometimes) and -/// Kyber512 (also referred to as `EphemeralKem` sometimes). -/// -/// See [rosenpass_oqs::ClassicMceliece460896] -/// and [rosenpass_oqs::Kyber512] for more details on the specific KEMS. -/// -pub mod kem { - pub use rosenpass_oqs::ClassicMceliece460896 as StaticKem; - pub use rosenpass_oqs::Kyber512 as EphemeralKem; -} diff --git a/ciphers/src/subtle/blake2b.rs b/ciphers/src/subtle/blake2b.rs deleted file mode 100644 index 26dbf257..00000000 --- a/ciphers/src/subtle/blake2b.rs +++ /dev/null @@ -1,65 +0,0 @@ -use zeroize::Zeroizing; - -use blake2::digest::crypto_common::generic_array::GenericArray; -use blake2::digest::crypto_common::typenum::U32; -use blake2::digest::crypto_common::KeySizeUser; -use blake2::digest::{FixedOutput, Mac, OutputSizeUser}; -use blake2::Blake2bMac; - -use rosenpass_to::{ops::copy_slice, with_destination, To}; -use rosenpass_util::typenum2const; - -/// Specify that the used implementation of BLAKE2b is the MAC version of BLAKE2b -/// with output and key length of 32 bytes (see [Blake2bMac]). -type Impl = Blake2bMac; - -type KeyLen = ::KeySize; -type OutLen = ::OutputSize; - -/// The key length for BLAKE2b supported by this API. Currently 32 Bytes. -const KEY_LEN: usize = typenum2const! { KeyLen }; -/// The output length for BLAKE2b supported by this API. Currently 32 Bytes. -const OUT_LEN: usize = typenum2const! { OutLen }; - -/// Minimal key length supported by this API. -pub const KEY_MIN: usize = KEY_LEN; -/// maximal key length supported by this API. -pub const KEY_MAX: usize = KEY_LEN; -/// minimal output length supported by this API. -pub const OUT_MIN: usize = OUT_LEN; -/// maximal output length supported by this API. -pub const OUT_MAX: usize = OUT_LEN; - -/// Hashes the given `data` with the [Blake2bMac] hash function under the given `key`. -/// The both the length of the output the length of the key 32 bytes (or 256 bits). -/// -/// # Examples -/// -///```rust -/// # use rosenpass_ciphers::subtle::blake2b::hash; -/// use rosenpass_to::To; -/// let zero_key: [u8; 32] = [0; 32]; -/// let data: [u8; 32] = [255; 32]; -/// // buffer for the hash output -/// let mut hash_data: [u8; 32] = [0u8; 32]; -/// -/// assert!(hash(&zero_key, &data).to(&mut hash_data).is_ok(), "Hashing has to return OK result"); -///``` -/// -#[inline] -pub fn hash<'a>(key: &'a [u8], data: &'a [u8]) -> impl To<[u8], anyhow::Result<()>> + 'a { - with_destination(|out: &mut [u8]| { - let mut h = Impl::new_from_slice(key)?; - h.update(data); - - // Jesus christ, blake2 crate, your usage of GenericArray might be nice and fancy - // but it introduces a ton of complexity. This cost me half an hour just to figure - // out the right way to use the imports while allowing for zeroization. - // An API based on slices might actually be simpler. - let mut tmp = Zeroizing::new([0u8; OUT_LEN]); - let tmp = GenericArray::from_mut_slice(tmp.as_mut()); - h.finalize_into(tmp); - copy_slice(tmp.as_ref()).to(out); - Ok(()) - }) -} diff --git a/ciphers/src/subtle/chacha20poly1305_ietf.rs b/ciphers/src/subtle/chacha20poly1305_ietf.rs deleted file mode 100644 index b979aff1..00000000 --- a/ciphers/src/subtle/chacha20poly1305_ietf.rs +++ /dev/null @@ -1,99 +0,0 @@ -use rosenpass_to::ops::copy_slice; -use rosenpass_to::To; -use rosenpass_util::typenum2const; - -use chacha20poly1305::aead::generic_array::GenericArray; -use chacha20poly1305::ChaCha20Poly1305 as AeadImpl; -use chacha20poly1305::{AeadCore, AeadInPlace, KeyInit, KeySizeUser}; - -/// The key length is 32 bytes or 256 bits. -pub const KEY_LEN: usize = typenum2const! { ::KeySize }; -/// The MAC tag length is 16 bytes or 128 bits. -pub const TAG_LEN: usize = typenum2const! { ::TagSize }; -/// The nonce length is 12 bytes or 96 bits. -pub const NONCE_LEN: usize = typenum2const! { ::NonceSize }; - -/// Encrypts using ChaCha20Poly1305 as implemented in [RustCrypto](https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305). -/// `key` MUST be chosen (pseudo-)randomly and `nonce` MOST NOT be reused. The `key` slice MUST have -/// a length of [KEY_LEN]. The `nonce` slice MUST have a length of [NONCE_LEN]. The last [TAG_LEN] bytes -/// written in `ciphertext` are the tag guaranteeing integrity. `ciphertext` MUST have a capacity of -/// `plaintext.len()` + [TAG_LEN]. -/// -/// # Examples -///```rust -/// # use rosenpass_ciphers::subtle::chacha20poly1305_ietf::{encrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; -/// -/// const PLAINTEXT_LEN: usize = 43; -/// let plaintext = "post-quantum cryptography is very important".as_bytes(); -/// assert_eq!(PLAINTEXT_LEN, plaintext.len()); -/// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY -/// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE -/// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); -/// let mut ciphertext_buffer = [0u8;PLAINTEXT_LEN + TAG_LEN]; -/// -/// let res: anyhow::Result<()> = encrypt(&mut ciphertext_buffer, key, nonce, additional_data, plaintext); -/// assert!(res.is_ok()); -/// # let expected_ciphertext: &[u8] = &[239, 104, 148, 202, 120, 32, 77, 27, 246, 206, 226, 17, -/// # 83, 78, 122, 116, 187, 123, 70, 199, 58, 130, 21, 1, 107, 230, 58, 77, 18, 152, 31, 159, 80, -/// # 151, 72, 27, 236, 137, 60, 55, 180, 31, 71, 97, 199, 12, 60, 155, 70, 221, 225, 110, 132, 191, -/// # 8, 114, 85, 4, 25]; -/// # assert_eq!(expected_ciphertext, &ciphertext_buffer); -///``` -#[inline] -pub fn encrypt( - ciphertext: &mut [u8], - key: &[u8], - nonce: &[u8], - ad: &[u8], - plaintext: &[u8], -) -> anyhow::Result<()> { - let nonce = GenericArray::from_slice(nonce); - let (ct, mac) = ciphertext.split_at_mut(ciphertext.len() - TAG_LEN); - copy_slice(plaintext).to(ct); - let mac_value = AeadImpl::new_from_slice(key)?.encrypt_in_place_detached(nonce, ad, ct)?; - copy_slice(&mac_value[..]).to(mac); - Ok(()) -} - -/// Decrypts a `ciphertext` and verifies the integrity of the `ciphertext` and the additional data -/// `ad`. using ChaCha20Poly1305 as implemented in [RustCrypto](https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305). -/// -/// The `key` slice MUST have a length of [KEY_LEN]. The `nonce` slice MUST have a length of -/// [NONCE_LEN]. The plaintext buffer must have a capacity of `ciphertext.len()` - [TAG_LEN]. -/// -/// # Examples -///```rust -/// # use rosenpass_ciphers::subtle::chacha20poly1305_ietf::{decrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; -/// let ciphertext: &[u8] = &[239, 104, 148, 202, 120, 32, 77, 27, 246, 206, 226, 17, -/// 83, 78, 122, 116, 187, 123, 70, 199, 58, 130, 21, 1, 107, 230, 58, 77, 18, 152, 31, 159, 80, -/// 151, 72, 27, 236, 137, 60, 55, 180, 31, 71, 97, 199, 12, 60, 155, 70, 221, 225, 110, 132, 191, -/// 8, 114, 85, 4, 25]; // this is the ciphertext generated by the example for the encryption -/// const PLAINTEXT_LEN: usize = 43; -/// assert_eq!(PLAINTEXT_LEN + TAG_LEN, ciphertext.len()); -/// -/// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY -/// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE -/// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); -/// let mut plaintext_buffer = [0u8; PLAINTEXT_LEN]; -/// -/// let res: anyhow::Result<()> = decrypt(&mut plaintext_buffer, key, nonce, additional_data, ciphertext); -/// assert!(res.is_ok()); -/// let expected_plaintext = "post-quantum cryptography is very important".as_bytes(); -/// assert_eq!(expected_plaintext, plaintext_buffer); -/// -///``` -#[inline] -pub fn decrypt( - plaintext: &mut [u8], - key: &[u8], - nonce: &[u8], - ad: &[u8], - ciphertext: &[u8], -) -> anyhow::Result<()> { - let nonce = GenericArray::from_slice(nonce); - let (ct, mac) = ciphertext.split_at(ciphertext.len() - TAG_LEN); - let tag = GenericArray::from_slice(mac); - copy_slice(ct).to(plaintext); - AeadImpl::new_from_slice(key)?.decrypt_in_place_detached(nonce, ad, plaintext, tag)?; - Ok(()) -} diff --git a/ciphers/src/subtle/chacha20poly1305_ietf_libcrux.rs b/ciphers/src/subtle/chacha20poly1305_ietf_libcrux.rs deleted file mode 100644 index ccf9735e..00000000 --- a/ciphers/src/subtle/chacha20poly1305_ietf_libcrux.rs +++ /dev/null @@ -1,117 +0,0 @@ -use rosenpass_to::ops::copy_slice; -use rosenpass_to::To; - -use zeroize::Zeroize; - -/// The key length is 32 bytes or 256 bits. -pub const KEY_LEN: usize = 32; // Grrrr! Libcrux, please provide me these constants. -/// The MAC tag length is 16 bytes or 128 bits. -pub const TAG_LEN: usize = 16; -/// The nonce length is 12 bytes or 96 bits. -pub const NONCE_LEN: usize = 12; - -/// Encrypts using ChaCha20Poly1305 as implemented in [libcrux](https://github.com/cryspen/libcrux). -/// Key and nonce MUST be chosen (pseudo-)randomly. The `key` slice MUST have a length of -/// [KEY_LEN]. The `nonce` slice MUST have a length of [NONCE_LEN]. The last [TAG_LEN] bytes -/// written in `ciphertext` are the tag guaranteeing integrity. `ciphertext` MUST have a capacity of -/// `plaintext.len()` + [TAG_LEN]. -/// -/// # Examples -///```rust -/// # use rosenpass_ciphers::subtle::chacha20poly1305_ietf_libcrux::{encrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; -/// -/// const PLAINTEXT_LEN: usize = 43; -/// let plaintext = "post-quantum cryptography is very important".as_bytes(); -/// assert_eq!(PLAINTEXT_LEN, plaintext.len()); -/// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY -/// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE -/// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); -/// let mut ciphertext_buffer = [0u8; PLAINTEXT_LEN + TAG_LEN]; -/// -/// let res: anyhow::Result<()> = encrypt(&mut ciphertext_buffer, key, nonce, additional_data, plaintext); -/// assert!(res.is_ok()); -/// # let expected_ciphertext: &[u8] = &[239, 104, 148, 202, 120, 32, 77, 27, 246, 206, 226, 17, -/// # 83, 78, 122, 116, 187, 123, 70, 199, 58, 130, 21, 1, 107, 230, 58, 77, 18, 152, 31, 159, 80, -/// # 151, 72, 27, 236, 137, 60, 55, 180, 31, 71, 97, 199, 12, 60, 155, 70, 221, 225, 110, 132, 191, -/// # 8, 114, 85, 4, 25]; -/// # assert_eq!(expected_ciphertext, &ciphertext_buffer); -///``` -/// -#[inline] -pub fn encrypt( - ciphertext: &mut [u8], - key: &[u8], - nonce: &[u8], - ad: &[u8], - plaintext: &[u8], -) -> anyhow::Result<()> { - let (ciphertext, mac) = ciphertext.split_at_mut(ciphertext.len() - TAG_LEN); - - use libcrux::aead as C; - let crux_key = C::Key::Chacha20Poly1305(C::Chacha20Key(key.try_into().unwrap())); - let crux_iv = C::Iv(nonce.try_into().unwrap()); - - copy_slice(plaintext).to(ciphertext); - let crux_tag = libcrux::aead::encrypt(&crux_key, ciphertext, crux_iv, ad).unwrap(); - copy_slice(crux_tag.as_ref()).to(mac); - - match crux_key { - C::Key::Chacha20Poly1305(mut k) => k.0.zeroize(), - _ => panic!(), - } - - Ok(()) -} - -/// Decrypts a `ciphertext` and verifies the integrity of the `ciphertext` and the additional data -/// `ad`. using ChaCha20Poly1305 as implemented in [libcrux](https://github.com/cryspen/libcrux). -/// -/// The `key` slice MUST have a length of [KEY_LEN]. The `nonce` slice MUST have a length of -/// [NONCE_LEN]. The plaintext buffer must have a capacity of `ciphertext.len()` - [TAG_LEN]. -/// -/// # Examples -///```rust -/// # use rosenpass_ciphers::subtle::chacha20poly1305_ietf_libcrux::{decrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; -/// let ciphertext: &[u8] = &[239, 104, 148, 202, 120, 32, 77, 27, 246, 206, 226, 17, -/// 83, 78, 122, 116, 187, 123, 70, 199, 58, 130, 21, 1, 107, 230, 58, 77, 18, 152, 31, 159, 80, -/// 151, 72, 27, 236, 137, 60, 55, 180, 31, 71, 97, 199, 12, 60, 155, 70, 221, 225, 110, 132, 191, -/// 8, 114, 85, 4, 25]; // this is the ciphertext generated by the example for the encryption -/// const PLAINTEXT_LEN: usize = 43; -/// assert_eq!(PLAINTEXT_LEN + TAG_LEN, ciphertext.len()); -/// -/// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY -/// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE -/// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); -/// let mut plaintext_buffer = [0u8; PLAINTEXT_LEN]; -/// -/// let res: anyhow::Result<()> = decrypt(&mut plaintext_buffer, key, nonce, additional_data, ciphertext); -/// assert!(res.is_ok()); -/// let expected_plaintext = "post-quantum cryptography is very important".as_bytes(); -/// assert_eq!(expected_plaintext, plaintext_buffer); -/// -///``` -#[inline] -pub fn decrypt( - plaintext: &mut [u8], - key: &[u8], - nonce: &[u8], - ad: &[u8], - ciphertext: &[u8], -) -> anyhow::Result<()> { - let (ciphertext, mac) = ciphertext.split_at(ciphertext.len() - TAG_LEN); - - use libcrux::aead as C; - let crux_key = C::Key::Chacha20Poly1305(C::Chacha20Key(key.try_into().unwrap())); - let crux_iv = C::Iv(nonce.try_into().unwrap()); - let crux_tag = C::Tag::from_slice(mac).unwrap(); - - copy_slice(ciphertext).to(plaintext); - libcrux::aead::decrypt(&crux_key, plaintext, crux_iv, ad, &crux_tag).unwrap(); - - match crux_key { - C::Key::Chacha20Poly1305(mut k) => k.0.zeroize(), - _ => panic!(), - } - - Ok(()) -} diff --git a/ciphers/src/subtle/custom/incorrect_hmac_blake2b.rs b/ciphers/src/subtle/custom/incorrect_hmac_blake2b.rs new file mode 100644 index 00000000..93101d53 --- /dev/null +++ b/ciphers/src/subtle/custom/incorrect_hmac_blake2b.rs @@ -0,0 +1,79 @@ +use rosenpass_cipher_traits::{ + algorithms::KeyedHashIncorrectHmacBlake2b, + primitives::{InferKeyedHash, KeyedHash, KeyedHashTo}, +}; +use rosenpass_constant_time::xor; +use rosenpass_to::{ops::copy_slice, To}; +use zeroize::Zeroizing; + +#[cfg(not(feature = "experiment_libcrux_blake2"))] +use crate::subtle::rust_crypto::blake2b::Blake2b; +#[cfg(not(feature = "experiment_libcrux_blake2"))] +use anyhow::Error; + +#[cfg(feature = "experiment_libcrux_blake2")] +use crate::subtle::libcrux::blake2b::{Blake2b, Error}; + +/// The key length, 32 bytes or 256 bits. +pub const KEY_LEN: usize = 32; + +/// The hash length, 32 bytes or 256 bits. +pub const HASH_LEN: usize = 32; + +/// This is a woefully incorrect implementation of hmac_blake2b. +/// See +/// +/// It accepts 32 byte keys, exclusively. +/// +/// This will be replaced, likely by Kekkac at some point soon. +/// +/// +/// # Examples +///```rust +/// # use rosenpass_ciphers::subtle::custom::incorrect_hmac_blake2b::IncorrectHmacBlake2bCore; +/// use rosenpass_cipher_traits::primitives::KeyedHashTo; +/// use rosenpass_to::To; +/// let key: [u8; 32] = [0; 32]; +/// let data: [u8; 32] = [255; 32]; +/// // buffer for the hash output +/// let mut hash_data: [u8; 32] = [0u8; 32]; +/// +/// assert!(IncorrectHmacBlake2bCore::keyed_hash_to(&key, &data).to(&mut hash_data).is_ok(), "Hashing has to return OK result"); +/// # let expected_hash: &[u8] = &[5, 152, 135, 141, 151, 106, 147, 8, 220, 95, 38, 66, 29, 33, 3, +/// 104, 250, 114, 131, 119, 27, 56, 59, 44, 11, 67, 230, 113, 112, 20, 80, 103]; +/// # assert_eq!(hash_data, expected_hash); +///``` +/// +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IncorrectHmacBlake2bCore; + +impl KeyedHash for IncorrectHmacBlake2bCore { + type Error = Error; + + fn keyed_hash( + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error> { + const IPAD: [u8; KEY_LEN] = [0x36u8; KEY_LEN]; + const OPAD: [u8; KEY_LEN] = [0x5Cu8; KEY_LEN]; + + type Key = Zeroizing<[u8; KEY_LEN]>; + let mut tmp_key = Key::default(); + + copy_slice(key).to(tmp_key.as_mut()); + xor(&IPAD).to(tmp_key.as_mut()); + let mut outer_data = Key::default(); + Blake2b::keyed_hash_to(&tmp_key, data).to(&mut outer_data)?; + + copy_slice(key).to(tmp_key.as_mut()); + xor(&OPAD).to(tmp_key.as_mut()); + Blake2b::keyed_hash_to(&tmp_key, outer_data.as_ref()).to(out)?; + + Ok(()) + } +} + +pub type IncorrectHmacBlake2b = InferKeyedHash; + +impl KeyedHashIncorrectHmacBlake2b for IncorrectHmacBlake2bCore {} diff --git a/ciphers/src/subtle/custom/mod.rs b/ciphers/src/subtle/custom/mod.rs new file mode 100644 index 00000000..642d8eaf --- /dev/null +++ b/ciphers/src/subtle/custom/mod.rs @@ -0,0 +1,3 @@ +//! Own implementations of custom algorithms + +pub mod incorrect_hmac_blake2b; diff --git a/ciphers/src/subtle/incorrect_hmac_blake2b.rs b/ciphers/src/subtle/incorrect_hmac_blake2b.rs deleted file mode 100644 index 0bc72cf0..00000000 --- a/ciphers/src/subtle/incorrect_hmac_blake2b.rs +++ /dev/null @@ -1,67 +0,0 @@ -use anyhow::ensure; -use zeroize::Zeroizing; - -use rosenpass_constant_time::xor; -use rosenpass_to::{ops::copy_slice, with_destination, To}; - -use crate::subtle::blake2b; - -/// The key length, 32 bytes or 256 bits. -pub const KEY_LEN: usize = 32; -/// The minimal key length, identical to [KEY_LEN] -pub const KEY_MIN: usize = KEY_LEN; -/// The maximal key length, identical to [KEY_LEN] -pub const KEY_MAX: usize = KEY_LEN; -/// The minimal output length, see [blake2b::OUT_MIN] -pub const OUT_MIN: usize = blake2b::OUT_MIN; -/// The maximal output length, see [blake2b::OUT_MAX] -pub const OUT_MAX: usize = blake2b::OUT_MAX; - -/// This is a woefully incorrect implementation of hmac_blake2b. -/// See -/// -/// It accepts 32 byte keys, exclusively. -/// -/// This will be replaced, likely by Kekkac at some point soon. -/// -/// -/// # Examples -///```rust -/// # use rosenpass_ciphers::subtle::incorrect_hmac_blake2b::hash; -/// use rosenpass_to::To; -/// let key: [u8; 32] = [0; 32]; -/// let data: [u8; 32] = [255; 32]; -/// // buffer for the hash output -/// let mut hash_data: [u8; 32] = [0u8; 32]; -/// -/// assert!(hash(&key, &data).to(&mut hash_data).is_ok(), "Hashing has to return OK result"); -/// # let expected_hash: &[u8] = &[5, 152, 135, 141, 151, 106, 147, 8, 220, 95, 38, 66, 29, 33, 3, -/// 104, 250, 114, 131, 119, 27, 56, 59, 44, 11, 67, 230, 113, 112, 20, 80, 103]; -/// # assert_eq!(hash_data, expected_hash); -///``` -/// -#[inline] -pub fn hash<'a>(key: &'a [u8], data: &'a [u8]) -> impl To<[u8], anyhow::Result<()>> + 'a { - const IPAD: [u8; KEY_LEN] = [0x36u8; KEY_LEN]; - const OPAD: [u8; KEY_LEN] = [0x5Cu8; KEY_LEN]; - - with_destination(|out: &mut [u8]| { - // Not bothering with padding; the implementation - // uses appropriately sized keys. - ensure!(key.len() == KEY_LEN); - - type Key = Zeroizing<[u8; KEY_LEN]>; - let mut tmp_key = Key::default(); - - copy_slice(key).to(tmp_key.as_mut()); - xor(&IPAD).to(tmp_key.as_mut()); - let mut outer_data = Key::default(); - blake2b::hash(tmp_key.as_ref(), data).to(outer_data.as_mut())?; - - copy_slice(key).to(tmp_key.as_mut()); - xor(&OPAD).to(tmp_key.as_mut()); - blake2b::hash(tmp_key.as_ref(), outer_data.as_ref()).to(out)?; - - Ok(()) - }) -} diff --git a/ciphers/src/subtle/keyed_hash.rs b/ciphers/src/subtle/keyed_hash.rs new file mode 100644 index 00000000..1a223418 --- /dev/null +++ b/ciphers/src/subtle/keyed_hash.rs @@ -0,0 +1,65 @@ +//! This module provides types that enabling choosing the keyed hash building block to be used at +//! runtime (using enums) instead of at compile time (using generics). + +use anyhow::Result; +use rosenpass_cipher_traits::primitives::KeyedHashInstance; +use std::fmt::Display; + +use crate::subtle::{ + custom::incorrect_hmac_blake2b::IncorrectHmacBlake2b, rust_crypto::keyed_shake256::SHAKE256_32, +}; + +/// Length of symmetric key throughout Rosenpass. +pub const KEY_LEN: usize = 32; + +/// The hash is used as a symmetric key and should have the same length. +pub const HASH_LEN: usize = KEY_LEN; + +/// Provides a way to pick which keyed hash to use at runtime. +/// Implements [`KeyedHashInstance`] to allow hashing using the respective algorithm. +#[derive(Debug, Eq, PartialEq, Clone)] +pub enum KeyedHash { + /// A hasher backed by [`SHAKE256_32`]. + KeyedShake256(SHAKE256_32), + /// A hasher backed by [`IncorrectHmacBlake2b`]. + IncorrectHmacBlake2b(IncorrectHmacBlake2b), +} + +impl KeyedHash { + /// Creates an [`KeyedHash`] backed by SHAKE256. + pub fn keyed_shake256() -> Self { + Self::KeyedShake256(Default::default()) + } + + /// Creates an [`KeyedHash`] backed by Blake2B. + pub fn incorrect_hmac_blake2b() -> Self { + Self::IncorrectHmacBlake2b(Default::default()) + } +} + +impl KeyedHashInstance for KeyedHash { + type Error = anyhow::Error; + + fn keyed_hash( + &self, + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error> { + match self { + Self::KeyedShake256(h) => h.keyed_hash(key, data, out)?, + Self::IncorrectHmacBlake2b(h) => h.keyed_hash(key, data, out)?, + }; + + Ok(()) + } +} + +impl Display for KeyedHash { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::KeyedShake256(_) => write!(f, "KeyedShake256_32"), + Self::IncorrectHmacBlake2b(_) => write!(f, "IncorrectHmacBlake2b"), + } + } +} diff --git a/ciphers/src/subtle/libcrux/blake2b.rs b/ciphers/src/subtle/libcrux/blake2b.rs new file mode 100644 index 00000000..9bb4f1de --- /dev/null +++ b/ciphers/src/subtle/libcrux/blake2b.rs @@ -0,0 +1,88 @@ +//! Implementation of the [`KeyedHashBlake2b`] trait based on the [`libcrux_blake2`] crate. + +use libcrux_blake2::Blake2bBuilder; + +use rosenpass_cipher_traits::algorithms::KeyedHashBlake2b; +use rosenpass_cipher_traits::primitives::KeyedHash; + +pub use rosenpass_cipher_traits::algorithms::keyed_hash_blake2b::HASH_LEN; +pub use rosenpass_cipher_traits::algorithms::keyed_hash_blake2b::KEY_LEN; + +/// Describles which error occurred +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// An unexpected internal error occurred. Should never be returned and points to a bug in the + /// implementation. + #[error("internal error")] + InternalError, + + /// Indicates that the provided data was too long. + #[error("data is too long")] + DataTooLong, +} + +/// Hasher for the given `data` with the Blake2b hash function. +pub struct Blake2b; + +impl KeyedHash for Blake2b { + type Error = Error; + + fn keyed_hash( + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error> { + let mut h = Blake2bBuilder::new_keyed_const(key) + // this may fail if the key length is invalid, but 32 is fine + .map_err(|_| Error::InternalError)? + .build_const_digest_len() + .map_err(|_| + // this can only fail if the output length is invalid, but 32 is fine. + Error::InternalError)?; + + h.update(data).map_err(|_| Error::DataTooLong)?; + h.finalize(out); + + Ok(()) + } +} + +impl KeyedHashBlake2b for Blake2b {} + +#[cfg(test)] +mod equivalence_tests { + use super::*; + use rand::RngCore; + + #[test] + fn fuzz_equivalence_libcrux_old_new() { + let datas: [&[u8]; 3] = [ + b"".as_slice(), + b"test".as_slice(), + b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", + ]; + + let mut key = [0; KEY_LEN]; + let mut rng = rand::thread_rng(); + + let mut hash_left = [0; 32]; + let mut hash_right = [0; 32]; + + for data in datas { + for _ in 0..1000 { + rng.fill_bytes(&mut key); + + crate::subtle::rust_crypto::blake2b::Blake2b::keyed_hash( + &key, + data, + &mut hash_left, + ) + .unwrap(); + crate::subtle::libcrux::blake2b::Blake2b::keyed_hash(&key, data, &mut hash_right) + .unwrap(); + + assert_eq!(hash_left, hash_right); + } + } + } +} diff --git a/ciphers/src/subtle/libcrux/chacha20poly1305_ietf.rs b/ciphers/src/subtle/libcrux/chacha20poly1305_ietf.rs new file mode 100644 index 00000000..1a402be3 --- /dev/null +++ b/ciphers/src/subtle/libcrux/chacha20poly1305_ietf.rs @@ -0,0 +1,274 @@ +//! Implementation of the [`AeadChaCha20Poly1305`] trait based on the [`libcrux_chacha20poly1305`] crate. + +use rosenpass_cipher_traits::algorithms::AeadChaCha20Poly1305; +use rosenpass_cipher_traits::primitives::{Aead, AeadError}; + +pub use rosenpass_cipher_traits::algorithms::aead_chacha20poly1305::{KEY_LEN, NONCE_LEN, TAG_LEN}; + +/// An implementation of the ChaCha20Poly1305 AEAD based on libcrux +pub struct ChaCha20Poly1305; + +impl Aead for ChaCha20Poly1305 { + fn encrypt( + &self, + ciphertext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + plaintext: &[u8], + ) -> Result<(), AeadError> { + let (ctxt, tag) = libcrux_chacha20poly1305::encrypt(key, plaintext, ciphertext, ad, nonce) + .map_err(|_| AeadError::InternalError)?; + + // return an error of the destination buffer is longer than expected + // because the caller wouldn't know where the end is + if ctxt.len() + tag.len() != ciphertext.len() { + return Err(AeadError::InternalError); + } + + Ok(()) + } + + fn decrypt( + &self, + plaintext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + ciphertext: &[u8], + ) -> Result<(), AeadError> { + let ptxt = libcrux_chacha20poly1305::decrypt(key, plaintext, ciphertext, ad, nonce) + .map_err(|_| AeadError::DecryptError)?; + + // return an error of the destination buffer is longer than expected + // because the caller wouldn't know where the end is + if ptxt.len() != plaintext.len() { + return Err(AeadError::DecryptError); + } + + Ok(()) + } +} + +impl AeadChaCha20Poly1305 for ChaCha20Poly1305 {} + +/// The idea of these tests is to check that the above implemenatation behaves, by and large, the +/// same as the one from the old libcrux and the one from RustCrypto. You can consider them janky, +/// self-rolled property-based tests. +#[cfg(test)] +mod equivalence_tests { + use super::*; + use rand::RngCore; + + #[test] + fn proptest_equivalence_libcrux_rustcrypto() { + use crate::subtle::rust_crypto::chacha20poly1305_ietf::ChaCha20Poly1305 as RustCryptoChaCha20Poly1305; + let ptxts: [&[u8]; 3] = [ + b"".as_slice(), + b"test".as_slice(), + b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", + ]; + let mut key = [0; KEY_LEN]; + let mut rng = rand::thread_rng(); + + let mut ctxt_left = [0; 64 + TAG_LEN]; + let mut ctxt_right = [0; 64 + TAG_LEN]; + + let mut ptxt_left = [0; 64]; + let mut ptxt_right = [0; 64]; + + let nonce = [0; NONCE_LEN]; + let ad = b""; + + for ptxt in ptxts { + for _ in 0..1000 { + rng.fill_bytes(&mut key); + let ctxt_left = &mut ctxt_left[..ptxt.len() + TAG_LEN]; + let ctxt_right = &mut ctxt_right[..ptxt.len() + TAG_LEN]; + + let ptxt_left = &mut ptxt_left[..ptxt.len()]; + let ptxt_right = &mut ptxt_right[..ptxt.len()]; + + RustCryptoChaCha20Poly1305 + .encrypt(ctxt_left, &key, &nonce, ad, ptxt) + .unwrap(); + ChaCha20Poly1305 + .encrypt(ctxt_right, &key, &nonce, ad, ptxt) + .unwrap(); + + assert_eq!(ctxt_left, ctxt_right); + + RustCryptoChaCha20Poly1305 + .decrypt(ptxt_left, &key, &nonce, ad, ctxt_left) + .unwrap(); + ChaCha20Poly1305 + .decrypt(ptxt_right, &key, &nonce, ad, ctxt_right) + .unwrap(); + + assert_eq!(ptxt_left, ptxt); + assert_eq!(ptxt_right, ptxt); + } + } + } + + #[test] + #[cfg(feature = "experiment_libcrux_chachapoly_test")] + fn proptest_equivalence_libcrux_old_new() { + let ptxts: [&[u8]; 3] = [ + b"".as_slice(), + b"test".as_slice(), + b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", + ]; + let mut key = [0; KEY_LEN]; + let mut rng = rand::thread_rng(); + + let mut ctxt_left = [0; 64 + TAG_LEN]; + let mut ctxt_right = [0; 64 + TAG_LEN]; + + let mut ptxt_left = [0; 64]; + let mut ptxt_right = [0; 64]; + + let nonce = [0; NONCE_LEN]; + let ad = b""; + + for ptxt in ptxts { + for _ in 0..1000 { + rng.fill_bytes(&mut key); + let ctxt_left = &mut ctxt_left[..ptxt.len() + TAG_LEN]; + let ctxt_right = &mut ctxt_right[..ptxt.len() + TAG_LEN]; + + let ptxt_left = &mut ptxt_left[..ptxt.len()]; + let ptxt_right = &mut ptxt_right[..ptxt.len()]; + + encrypt(ctxt_left, &key, &nonce, ad, ptxt).unwrap(); + ChaCha20Poly1305 + .encrypt(ctxt_right, &key, &nonce, ad, ptxt) + .unwrap(); + + assert_eq!(ctxt_left, ctxt_right); + + decrypt(ptxt_left, &key, &nonce, ad, ctxt_left).unwrap(); + ChaCha20Poly1305 + .decrypt(ptxt_right, &key, &nonce, ad, ctxt_right) + .unwrap(); + + assert_eq!(ptxt_left, ptxt); + assert_eq!(ptxt_right, ptxt); + } + } + + // The old libcrux functions: + + // The functions below are from the old libcrux backend. I am keeping them around so we can + // check if they behave the same. + use rosenpass_to::ops::copy_slice; + use rosenpass_to::To; + use zeroize::Zeroize; + + /// Encrypts using ChaCha20Poly1305 as implemented in [libcrux](https://github.com/cryspen/libcrux). + /// Key and nonce MUST be chosen (pseudo-)randomly. The `key` slice MUST have a length of + /// [KEY_LEN]. The `nonce` slice MUST have a length of [NONCE_LEN]. The last [TAG_LEN] bytes + /// written in `ciphertext` are the tag guaranteeing integrity. `ciphertext` MUST have a capacity of + /// `plaintext.len()` + [TAG_LEN]. + /// + /// # Examples + ///```rust + /// # use rosenpass_ciphers::subtle::chacha20poly1305_ietf_libcrux::{encrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; + /// + /// const PLAINTEXT_LEN: usize = 43; + /// let plaintext = "post-quantum cryptography is very important".as_bytes(); + /// assert_eq!(PLAINTEXT_LEN, plaintext.len()); + /// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY + /// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE + /// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); + /// let mut ciphertext_buffer = [0u8; PLAINTEXT_LEN + TAG_LEN]; + /// + /// let res: anyhow::Result<()> = encrypt(&mut ciphertext_buffer, key, nonce, additional_data, plaintext); + /// assert!(res.is_ok()); + /// # let expected_ciphertext: &[u8] = &[239, 104, 148, 202, 120, 32, 77, 27, 246, 206, 226, 17, + /// # 83, 78, 122, 116, 187, 123, 70, 199, 58, 130, 21, 1, 107, 230, 58, 77, 18, 152, 31, 159, 80, + /// # 151, 72, 27, 236, 137, 60, 55, 180, 31, 71, 97, 199, 12, 60, 155, 70, 221, 225, 110, 132, 191, + /// # 8, 114, 85, 4, 25]; + /// # assert_eq!(expected_ciphertext, &ciphertext_buffer); + ///``` + /// + #[inline] + pub fn encrypt( + ciphertext: &mut [u8], + key: &[u8], + nonce: &[u8], + ad: &[u8], + plaintext: &[u8], + ) -> anyhow::Result<()> { + let (ciphertext, mac) = ciphertext.split_at_mut(ciphertext.len() - TAG_LEN); + + use libcrux::aead as C; + let crux_key = C::Key::Chacha20Poly1305(C::Chacha20Key(key.try_into().unwrap())); + let crux_iv = C::Iv(nonce.try_into().unwrap()); + + copy_slice(plaintext).to(ciphertext); + let crux_tag = libcrux::aead::encrypt(&crux_key, ciphertext, crux_iv, ad).unwrap(); + copy_slice(crux_tag.as_ref()).to(mac); + + match crux_key { + C::Key::Chacha20Poly1305(mut k) => k.0.zeroize(), + _ => panic!(), + } + + Ok(()) + } + + /// Decrypts a `ciphertext` and verifies the integrity of the `ciphertext` and the additional data + /// `ad`. using ChaCha20Poly1305 as implemented in [libcrux](https://github.com/cryspen/libcrux). + /// + /// The `key` slice MUST have a length of [KEY_LEN]. The `nonce` slice MUST have a length of + /// [NONCE_LEN]. The plaintext buffer must have a capacity of `ciphertext.len()` - [TAG_LEN]. + /// + /// # Examples + ///```rust + /// # use rosenpass_ciphers::subtle::chacha20poly1305_ietf_libcrux::{decrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; + /// let ciphertext: &[u8] = &[239, 104, 148, 202, 120, 32, 77, 27, 246, 206, 226, 17, + /// 83, 78, 122, 116, 187, 123, 70, 199, 58, 130, 21, 1, 107, 230, 58, 77, 18, 152, 31, 159, 80, + /// 151, 72, 27, 236, 137, 60, 55, 180, 31, 71, 97, 199, 12, 60, 155, 70, 221, 225, 110, 132, 191, + /// 8, 114, 85, 4, 25]; // this is the ciphertext generated by the example for the encryption + /// const PLAINTEXT_LEN: usize = 43; + /// assert_eq!(PLAINTEXT_LEN + TAG_LEN, ciphertext.len()); + /// + /// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY + /// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE + /// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); + /// let mut plaintext_buffer = [0u8; PLAINTEXT_LEN]; + /// + /// let res: anyhow::Result<()> = decrypt(&mut plaintext_buffer, key, nonce, additional_data, ciphertext); + /// assert!(res.is_ok()); + /// let expected_plaintext = "post-quantum cryptography is very important".as_bytes(); + /// assert_eq!(expected_plaintext, plaintext_buffer); + /// + ///``` + #[inline] + pub fn decrypt( + plaintext: &mut [u8], + key: &[u8], + nonce: &[u8], + ad: &[u8], + ciphertext: &[u8], + ) -> anyhow::Result<()> { + let (ciphertext, mac) = ciphertext.split_at(ciphertext.len() - TAG_LEN); + + use libcrux::aead as C; + let crux_key = C::Key::Chacha20Poly1305(C::Chacha20Key(key.try_into().unwrap())); + let crux_iv = C::Iv(nonce.try_into().unwrap()); + let crux_tag = C::Tag::from_slice(mac).unwrap(); + + copy_slice(ciphertext).to(plaintext); + libcrux::aead::decrypt(&crux_key, plaintext, crux_iv, ad, &crux_tag).unwrap(); + + match crux_key { + C::Key::Chacha20Poly1305(mut k) => k.0.zeroize(), + _ => panic!(), + } + + Ok(()) + } + } +} diff --git a/ciphers/src/subtle/libcrux/kyber512.rs b/ciphers/src/subtle/libcrux/kyber512.rs new file mode 100644 index 00000000..34f7a80a --- /dev/null +++ b/ciphers/src/subtle/libcrux/kyber512.rs @@ -0,0 +1,133 @@ +//! Implementation of the [`KemKyber512`] trait based on the [`libcrux_ml_kem`] crate. + +use libcrux_ml_kem::kyber512; +use rand::RngCore; + +use rosenpass_cipher_traits::algorithms::KemKyber512; +use rosenpass_cipher_traits::primitives::{Kem, KemError}; + +pub use rosenpass_cipher_traits::algorithms::kem_kyber512::{CT_LEN, PK_LEN, SHK_LEN, SK_LEN}; + +/// An implementation of the Kyber512 KEM based on libcrux +pub struct Kyber512; + +impl Kem for Kyber512 { + fn keygen(&self, sk: &mut [u8; SK_LEN], pk: &mut [u8; PK_LEN]) -> Result<(), KemError> { + let mut randomness = [0u8; libcrux_ml_kem::KEY_GENERATION_SEED_SIZE]; + rand::thread_rng().fill_bytes(&mut randomness); + + let key_pair = kyber512::generate_key_pair(randomness); + + let new_sk: &[u8; SK_LEN] = key_pair.sk(); + let new_pk: &[u8; PK_LEN] = key_pair.pk(); + + sk.clone_from_slice(new_sk); + pk.clone_from_slice(new_pk); + + Ok(()) + } + + fn encaps( + &self, + shk: &mut [u8; SHK_LEN], + ct: &mut [u8; CT_LEN], + pk: &[u8; PK_LEN], + ) -> Result<(), KemError> { + let mut randomness = [0u8; libcrux_ml_kem::SHARED_SECRET_SIZE]; + rand::thread_rng().fill_bytes(&mut randomness); + + let (new_ct, new_shk) = kyber512::encapsulate(&pk.into(), randomness); + let new_ct: &[u8; CT_LEN] = new_ct.as_slice(); + + shk.clone_from_slice(&new_shk); + ct.clone_from_slice(new_ct); + + Ok(()) + } + + fn decaps( + &self, + shk: &mut [u8; SHK_LEN], + sk: &[u8; SK_LEN], + ct: &[u8; CT_LEN], + ) -> Result<(), KemError> { + let new_shk: [u8; SHK_LEN] = kyber512::decapsulate(&sk.into(), &ct.into()); + shk.clone_from(&new_shk); + Ok(()) + } +} + +impl Default for Kyber512 { + fn default() -> Self { + Self + } +} + +impl KemKyber512 for Kyber512 {} + +#[cfg(test)] +mod equivalence_tests { + use super::*; + + // Test that libcrux and OQS produce the same results + #[test] + fn proptest_equivalence_libcrux_oqs() { + use rosenpass_oqs::Kyber512 as OqsKyber512; + + let (mut sk1, mut pk1) = ([0; SK_LEN], [0; PK_LEN]); + let (mut sk2, mut pk2) = ([0; SK_LEN], [0; PK_LEN]); + + let mut ct_left = [0; CT_LEN]; + let mut ct_right = [0; CT_LEN]; + + let mut shk_enc_left = [0; SHK_LEN]; + let mut shk_enc_right = [0; SHK_LEN]; + + // naming schema: shk_dec_{encapsing lib}_{decapsing lib} + // should be the same if the encapsing lib was the same. + let mut shk_dec_left_left = [0; SHK_LEN]; + let mut shk_dec_left_right = [0; SHK_LEN]; + let mut shk_dec_right_left = [0; SHK_LEN]; + let mut shk_dec_right_right = [0; SHK_LEN]; + + for _ in 0..1000 { + let sk1 = &mut sk1; + let pk1 = &mut pk1; + let sk2 = &mut sk2; + let pk2 = &mut pk2; + + let ct_left = &mut ct_left; + let ct_right = &mut ct_right; + + let shk_enc_left = &mut shk_enc_left; + let shk_enc_right = &mut shk_enc_right; + + let shk_dec_left_left = &mut shk_dec_left_left; + let shk_dec_left_right = &mut shk_dec_left_right; + let shk_dec_right_left = &mut shk_dec_right_left; + let shk_dec_right_right = &mut shk_dec_right_right; + + Kyber512.keygen(sk1, pk1).unwrap(); + Kyber512.keygen(sk2, pk2).unwrap(); + + Kyber512.encaps(shk_enc_left, ct_left, pk2).unwrap(); + OqsKyber512.encaps(shk_enc_right, ct_right, pk2).unwrap(); + + Kyber512.decaps(shk_dec_left_left, sk2, ct_left).unwrap(); + Kyber512.decaps(shk_dec_right_left, sk2, ct_right).unwrap(); + + OqsKyber512 + .decaps(shk_dec_left_right, sk2, ct_left) + .unwrap(); + OqsKyber512 + .decaps(shk_dec_right_right, sk2, ct_right) + .unwrap(); + + assert_eq!(shk_enc_left, shk_dec_left_left); + assert_eq!(shk_enc_left, shk_dec_left_right); + + assert_eq!(shk_enc_right, shk_dec_right_left); + assert_eq!(shk_enc_right, shk_dec_right_right); + } + } +} diff --git a/ciphers/src/subtle/libcrux/mod.rs b/ciphers/src/subtle/libcrux/mod.rs new file mode 100644 index 00000000..f481e535 --- /dev/null +++ b/ciphers/src/subtle/libcrux/mod.rs @@ -0,0 +1,14 @@ +//! Implementations backed by libcrux, a verified crypto library. +//! +//! [Website](https://cryspen.com/libcrux/) +//! +//! [Github](https://github.com/cryspen/libcrux) + +#[cfg(feature = "experiment_libcrux_define_blake2")] +pub mod blake2b; + +#[cfg(feature = "experiment_libcrux_define_chachapoly")] +pub mod chacha20poly1305_ietf; + +#[cfg(feature = "experiment_libcrux_define_kyber")] +pub mod kyber512; diff --git a/ciphers/src/subtle/mod.rs b/ciphers/src/subtle/mod.rs index 7e9431b7..6d3083b2 100644 --- a/ciphers/src/subtle/mod.rs +++ b/ciphers/src/subtle/mod.rs @@ -1,13 +1,16 @@ -/// This module provides the following cryptographic schemes: -/// - [blake2b]: The blake2b hash function -/// - [chacha20poly1305_ietf]: The Chacha20Poly1305 AEAD as implemented in [RustCrypto](https://crates.io/crates/chacha20poly1305) (only used when the feature `experiment_libcrux` is disabled). -/// - [chacha20poly1305_ietf_libcrux]: The Chacha20Poly1305 AEAD as implemented in [libcrux](https://github.com/cryspen/libcrux) (only used when the feature `experiment_libcrux` is enabled). -/// - [incorrect_hmac_blake2b]: An (incorrect) hmac based on [blake2b]. -/// - [xchacha20poly1305_ietf] The Chacha20Poly1305 AEAD as implemented in [RustCrypto](https://crates.io/crates/chacha20poly1305) -pub mod blake2b; -#[cfg(not(feature = "experiment_libcrux"))] -pub mod chacha20poly1305_ietf; -#[cfg(feature = "experiment_libcrux")] -pub mod chacha20poly1305_ietf_libcrux; -pub mod incorrect_hmac_blake2b; -pub mod xchacha20poly1305_ietf; +//! Contains the implementations of the crypto algorithms used throughout Rosenpass. + +pub mod keyed_hash; + +pub use custom::incorrect_hmac_blake2b; +pub use rust_crypto::{blake2b, keyed_shake256}; + +pub mod custom; +pub mod rust_crypto; + +#[cfg(any( + feature = "experiment_libcrux_define_blake2", + feature = "experiment_libcrux_define_chachapoly", + feature = "experiment_libcrux_define_kyber", +))] +pub mod libcrux; diff --git a/ciphers/src/subtle/rust_crypto/blake2b.rs b/ciphers/src/subtle/rust_crypto/blake2b.rs new file mode 100644 index 00000000..c391297f --- /dev/null +++ b/ciphers/src/subtle/rust_crypto/blake2b.rs @@ -0,0 +1,44 @@ +use zeroize::Zeroizing; + +use blake2::digest::crypto_common::generic_array::GenericArray; +use blake2::digest::crypto_common::typenum::U32; +use blake2::digest::{FixedOutput, Mac}; +use blake2::Blake2bMac; + +use rosenpass_cipher_traits::primitives::KeyedHash; +use rosenpass_to::{ops::copy_slice, To}; + +pub use rosenpass_cipher_traits::algorithms::keyed_hash_blake2b::{HASH_LEN, KEY_LEN}; + +/// Specify that the used implementation of BLAKE2b is the MAC version of BLAKE2b +/// with output and key length of 32 bytes (see [Blake2bMac]). +type Impl = Blake2bMac; + +/// Hashes the given `data` with the [Blake2bMac] hash function under the given `key`. +/// The both the length of the output the length of the key 32 bytes (or 256 bits). +pub struct Blake2b; + +impl KeyedHash for Blake2b { + type Error = anyhow::Error; + + fn keyed_hash( + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error> { + let mut h = Impl::new_from_slice(key)?; + h.update(data); + + // Jesus christ, blake2 crate, your usage of GenericArray might be nice and fancy, + // but it introduces a ton of complexity. This cost me half an hour just to figure + // out the right way to use the imports while allowing for zeroization. + // An API based on slices might actually be simpler. + let mut tmp = Zeroizing::new([0u8; HASH_LEN]); + let tmp = GenericArray::from_mut_slice(tmp.as_mut()); + h.finalize_into(tmp); + copy_slice(tmp.as_ref()).to(out); + Ok(()) + } +} + +impl rosenpass_cipher_traits::algorithms::KeyedHashBlake2b for Blake2b {} diff --git a/ciphers/src/subtle/rust_crypto/chacha20poly1305_ietf.rs b/ciphers/src/subtle/rust_crypto/chacha20poly1305_ietf.rs new file mode 100644 index 00000000..7f0a114c --- /dev/null +++ b/ciphers/src/subtle/rust_crypto/chacha20poly1305_ietf.rs @@ -0,0 +1,79 @@ +use rosenpass_to::ops::copy_slice; +use rosenpass_to::To; + +use rosenpass_cipher_traits::algorithms::AeadChaCha20Poly1305; +use rosenpass_cipher_traits::primitives::{Aead, AeadError}; + +use chacha20poly1305::aead::generic_array::GenericArray; +use chacha20poly1305::ChaCha20Poly1305 as AeadImpl; +use chacha20poly1305::{AeadInPlace, KeyInit}; + +pub use rosenpass_cipher_traits::algorithms::aead_chacha20poly1305::{KEY_LEN, NONCE_LEN, TAG_LEN}; + +/// Implements the [`Aead`] and [`AeadChaCha20Poly1305`] traits backed by the RustCrypto +/// implementation. +pub struct ChaCha20Poly1305; + +impl Aead for ChaCha20Poly1305 { + fn encrypt( + &self, + ciphertext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + plaintext: &[u8], + ) -> Result<(), AeadError> { + // The comparison looks complicated, but we need to do it this way to prevent + // over/underflows. + if ciphertext.len() < TAG_LEN || ciphertext.len() - TAG_LEN < plaintext.len() { + return Err(AeadError::InvalidLengths); + } + + let nonce = GenericArray::from_slice(nonce); + let (ct, mac) = ciphertext.split_at_mut(ciphertext.len() - TAG_LEN); + copy_slice(plaintext).to(ct); + + // This only fails if the length is wrong, which really shouldn't happen and would + // constitute an internal error. + let encrypter = AeadImpl::new_from_slice(key).map_err(|_| AeadError::InternalError)?; + + let mac_value = encrypter + .encrypt_in_place_detached(nonce, ad, ct) + .map_err(|_| AeadError::InternalError)?; + copy_slice(&mac_value[..]).to(mac); + + Ok(()) + } + + fn decrypt( + &self, + plaintext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + ciphertext: &[u8], + ) -> Result<(), AeadError> { + // The comparison looks complicated, but we need to do it this way to prevent + // over/underflows. + if ciphertext.len() < TAG_LEN || ciphertext.len() - TAG_LEN < plaintext.len() { + return Err(AeadError::InvalidLengths); + } + + let nonce = GenericArray::from_slice(nonce); + let (ct, mac) = ciphertext.split_at(ciphertext.len() - TAG_LEN); + let tag = GenericArray::from_slice(mac); + copy_slice(ct).to(plaintext); + + // This only fails if the length is wrong, which really shouldn't happen and would + // constitute an internal error. + let decrypter = AeadImpl::new_from_slice(key).map_err(|_| AeadError::InternalError)?; + + decrypter + .decrypt_in_place_detached(nonce, ad, plaintext, tag) + .map_err(|_| AeadError::DecryptError)?; + + Ok(()) + } +} + +impl AeadChaCha20Poly1305 for ChaCha20Poly1305 {} diff --git a/ciphers/src/subtle/rust_crypto/keyed_shake256.rs b/ciphers/src/subtle/rust_crypto/keyed_shake256.rs new file mode 100644 index 00000000..9474761f --- /dev/null +++ b/ciphers/src/subtle/rust_crypto/keyed_shake256.rs @@ -0,0 +1,117 @@ +use anyhow::ensure; +use rosenpass_cipher_traits::primitives::{InferKeyedHash, KeyedHash}; +use sha3::digest::{ExtendableOutput, Update, XofReader}; +use sha3::Shake256; + +pub use rosenpass_cipher_traits::algorithms::keyed_hash_shake256::{HASH_LEN, KEY_LEN}; + +/// An implementation of the [`KeyedHash`] trait backed by the RustCrypto implementation of SHAKE256. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SHAKE256Core; + +impl KeyedHash + for SHAKE256Core +{ + type Error = anyhow::Error; + + /// Provides a keyed hash function based on SHAKE256. To work for the protocol, the output length + /// and key length are fixed to 32 bytes (also see [KEY_LEN] and [HASH_LEN]). + /// + /// Note that the SHAKE256 is designed for 64 bytes output length, which we truncate to 32 bytes + /// to work well with the overall protocol. Referring to Table 4 of FIPS 202, this offers the + /// same collision resistance as SHAKE128, but 256 bits of preimage resistance. We therefore + /// prefer a truncated SHAKE256 over SHAKE128. + /// + /// #Examples + /// ```rust + /// # use rosenpass_ciphers::subtle::rust_crypto::keyed_shake256::SHAKE256Core; + /// use rosenpass_cipher_traits::primitives::KeyedHash; + /// const KEY_LEN: usize = 32; + /// const HASH_LEN: usize = 32; + /// let key: [u8; 32] = [0; KEY_LEN]; + /// let data: [u8; 32] = [255; 32]; // arbitrary data, could also be longer + /// // buffer for the hash output + /// let mut hash_data: [u8; 32] = [0u8; HASH_LEN]; + /// + /// assert!(SHAKE256Core::<32, 32>::keyed_hash(&key, &data, &mut hash_data).is_ok(), "Hashing has to return OK result"); + /// # let expected_hash: &[u8] = &[174, 4, 47, 188, 1, 228, 179, 246, 67, 43, 255, 94, 155, 11, + /// 187, 161, 38, 110, 217, 23, 4, 62, 172, 30, 218, 187, 249, 80, 171, 21, 145, 238]; + /// # assert_eq!(hash_data, expected_hash); + /// ``` + fn keyed_hash( + key: &[u8; KEY_LEN], + data: &[u8], + out: &mut [u8; HASH_LEN], + ) -> Result<(), Self::Error> { + // Since SHAKE256 is a XOF, we fix the output length manually to what is required for the + // protocol. + ensure!(out.len() == HASH_LEN); + // Not bothering with padding; the implementation + // uses appropriately sized keys. + ensure!(key.len() == KEY_LEN); + let mut shake256 = Shake256::default(); + shake256.update(key); + shake256.update(data); + + // Since we use domain separation extensively, related outputs of the truncated XOF + // are not a concern. This follows the NIST recommendations in Section A.2 of the FIPS 202 + // standard, (pages 24/25, i.e., 32/33 in the PDF). + shake256.finalize_xof().read(out); + Ok(()) + } +} + +impl SHAKE256Core { + pub fn new() -> Self { + Self + } +} + +impl Default for SHAKE256Core { + fn default() -> Self { + Self::new() + } +} + +/// This type provides the same functionality as [SHAKE256Core], but bound to an instance. +/// In contrast to [SHAKE256Core], this allows for type interference and thus allows the user of the +/// type to omit explicit type parameters when instantiating the type or using it. +/// +/// The instantiation is based on the [InferKeyedHash] trait. +/// +/// ```rust +/// # use rosenpass_ciphers::subtle::rust_crypto::keyed_shake256::{SHAKE256}; +/// use rosenpass_cipher_traits::primitives::KeyedHashInstance; +/// const KEY_LEN: usize = 32; +/// const HASH_LEN: usize = 32; +/// let key: [u8; KEY_LEN] = [0; KEY_LEN]; +/// let data: [u8; 32] = [255; 32]; // arbitrary data, could also be longer +/// // buffer for the hash output +/// let mut hash_data: [u8; 32] = [0u8; HASH_LEN]; +/// assert!(SHAKE256::new().keyed_hash(&key, &data, &mut hash_data).is_ok(), "Hashing has to return OK result"); +/// # let expected_hash: &[u8] = &[174, 4, 47, 188, 1, 228, 179, 246, 67, 43, 255, 94, 155, 11, 187, +/// 161, 38, 110, 217, 23, 4, 62, 172, 30, 218, 187, 249, 80, 171, 21, 145, 238]; +/// # assert_eq!(hash_data, expected_hash); +/// ``` +pub type SHAKE256 = + InferKeyedHash, KEY_LEN, HASH_LEN>; + +/// The SHAKE256_32 type is a specific instance of the [SHAKE256] type with the key length and hash +/// length fixed to 32 bytes. +/// +/// ```rust +/// # use rosenpass_ciphers::subtle::keyed_shake256::{SHAKE256_32}; +/// use rosenpass_cipher_traits::primitives::KeyedHashInstance; +/// const KEY_LEN: usize = 32; +/// const HASH_LEN: usize = 32; +/// let key: [u8; 32] = [0; KEY_LEN]; +/// let data: [u8; 32] = [255; 32]; // arbitrary data, could also be longer +/// // buffer for the hash output +/// let mut hash_data: [u8; 32] = [0u8; HASH_LEN]; +/// +/// assert!(SHAKE256_32::new().keyed_hash(&key, &data, &mut hash_data).is_ok(), "Hashing has to return OK result"); +/// # let expected_hash: &[u8] = &[174, 4, 47, 188, 1, 228, 179, 246, 67, 43, 255, 94, 155, 11, 187, +/// 161, 38, 110, 217, 23, 4, 62, 172, 30, 218, 187, 249, 80, 171, 21, 145, 238]; +/// # assert_eq!(hash_data, expected_hash); +/// ``` +pub type SHAKE256_32 = SHAKE256<32, 32>; diff --git a/ciphers/src/subtle/rust_crypto/mod.rs b/ciphers/src/subtle/rust_crypto/mod.rs new file mode 100644 index 00000000..062ef105 --- /dev/null +++ b/ciphers/src/subtle/rust_crypto/mod.rs @@ -0,0 +1,7 @@ +//! Implementations backed by RustCrypto + +pub mod blake2b; +pub mod keyed_shake256; + +pub mod chacha20poly1305_ietf; +pub mod xchacha20poly1305_ietf; diff --git a/ciphers/src/subtle/xchacha20poly1305_ietf.rs b/ciphers/src/subtle/rust_crypto/xchacha20poly1305_ietf.rs similarity index 51% rename from ciphers/src/subtle/xchacha20poly1305_ietf.rs rename to ciphers/src/subtle/rust_crypto/xchacha20poly1305_ietf.rs index 12a8ed8b..ce02f359 100644 --- a/ciphers/src/subtle/xchacha20poly1305_ietf.rs +++ b/ciphers/src/subtle/rust_crypto/xchacha20poly1305_ietf.rs @@ -1,17 +1,82 @@ use rosenpass_to::ops::copy_slice; use rosenpass_to::To; -use rosenpass_util::typenum2const; + +use rosenpass_cipher_traits::algorithms::aead_xchacha20poly1305::AeadXChaCha20Poly1305; +use rosenpass_cipher_traits::primitives::{Aead, AeadError, AeadWithNonceInCiphertext}; use chacha20poly1305::aead::generic_array::GenericArray; use chacha20poly1305::XChaCha20Poly1305 as AeadImpl; -use chacha20poly1305::{AeadCore, AeadInPlace, KeyInit, KeySizeUser}; +use chacha20poly1305::{AeadInPlace, KeyInit}; -/// The key length is 32 bytes or 256 bits. -pub const KEY_LEN: usize = typenum2const! { ::KeySize }; -/// The MAC tag length is 16 bytes or 128 bits. -pub const TAG_LEN: usize = typenum2const! { ::TagSize }; -/// The nonce length is 24 bytes or 192 bits. -pub const NONCE_LEN: usize = typenum2const! { ::NonceSize }; +pub use rosenpass_cipher_traits::algorithms::aead_xchacha20poly1305::{ + KEY_LEN, NONCE_LEN, TAG_LEN, +}; +/// Implements the [`Aead`] and [`AeadXChaCha20Poly1305`] traits backed by the RustCrypto +/// implementation. +pub struct XChaCha20Poly1305; + +impl Aead for XChaCha20Poly1305 { + fn encrypt( + &self, + ciphertext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + plaintext: &[u8], + ) -> Result<(), AeadError> { + // The comparison looks complicated, but we need to do it this way to prevent + // over/underflows. + if ciphertext.len() < TAG_LEN || ciphertext.len() - TAG_LEN < plaintext.len() { + return Err(AeadError::InvalidLengths); + } + + let (ct, mac) = ciphertext.split_at_mut(ciphertext.len() - TAG_LEN); + copy_slice(plaintext).to(ct); + + let nonce = GenericArray::from_slice(nonce); + + // This only fails if the length is wrong, which really shouldn't happen and would + // constitute an internal error. + let encrypter = AeadImpl::new_from_slice(key).map_err(|_| AeadError::InternalError)?; + + let mac_value = encrypter + .encrypt_in_place_detached(nonce, ad, ct) + .map_err(|_| AeadError::InternalError)?; + copy_slice(&mac_value[..]).to(mac); + Ok(()) + } + + fn decrypt( + &self, + plaintext: &mut [u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + ad: &[u8], + ciphertext: &[u8], + ) -> Result<(), AeadError> { + // The comparison looks complicated, but we need to do it this way to prevent + // over/underflows. + if ciphertext.len() < TAG_LEN || ciphertext.len() - TAG_LEN < plaintext.len() { + return Err(AeadError::InvalidLengths); + } + + let (ct, mac) = ciphertext.split_at(ciphertext.len() - TAG_LEN); + let nonce = GenericArray::from_slice(nonce); + let tag = GenericArray::from_slice(mac); + copy_slice(ct).to(plaintext); + + // This only fails if the length is wrong, which really shouldn't happen and would + // constitute an internal error. + let decrypter = AeadImpl::new_from_slice(key).map_err(|_| AeadError::InternalError)?; + + decrypter + .decrypt_in_place_detached(nonce, ad, plaintext, tag) + .map_err(|_| AeadError::DecryptError)?; + Ok(()) + } +} + +impl AeadXChaCha20Poly1305 for XChaCha20Poly1305 {} /// Encrypts using XChaCha20Poly1305 as implemented in [RustCrypto](https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305). /// `key` and `nonce` MUST be chosen (pseudo-)randomly. The `key` slice MUST have a length of @@ -23,12 +88,12 @@ pub const NONCE_LEN: usize = typenum2const! { ::NonceSize /// /// # Examples ///```rust -/// # use rosenpass_ciphers::subtle::xchacha20poly1305_ietf::{encrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; +/// # use rosenpass_ciphers::subtle::rust_crypto::xchacha20poly1305_ietf::{encrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; /// const PLAINTEXT_LEN: usize = 43; /// let plaintext = "post-quantum cryptography is very important".as_bytes(); /// assert_eq!(PLAINTEXT_LEN, plaintext.len()); -/// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY -/// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE +/// let key: &[u8; KEY_LEN] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY +/// let nonce: &[u8; NONCE_LEN] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE /// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); /// let mut ciphertext_buffer = [0u8; NONCE_LEN + PLAINTEXT_LEN + TAG_LEN]; /// @@ -44,19 +109,14 @@ pub const NONCE_LEN: usize = typenum2const! { ::NonceSize #[inline] pub fn encrypt( ciphertext: &mut [u8], - key: &[u8], - nonce: &[u8], + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], ad: &[u8], plaintext: &[u8], ) -> anyhow::Result<()> { - let nonce = GenericArray::from_slice(nonce); - let (n, ct_mac) = ciphertext.split_at_mut(NONCE_LEN); - let (ct, mac) = ct_mac.split_at_mut(ct_mac.len() - TAG_LEN); - copy_slice(nonce).to(n); - copy_slice(plaintext).to(ct); - let mac_value = AeadImpl::new_from_slice(key)?.encrypt_in_place_detached(nonce, ad, ct)?; - copy_slice(&mac_value[..]).to(mac); - Ok(()) + XChaCha20Poly1305 + .encrypt_with_nonce_in_ctxt(ciphertext, key, nonce, ad, plaintext) + .map_err(anyhow::Error::from) } /// Decrypts a `ciphertext` and verifies the integrity of the `ciphertext` and the additional data @@ -71,7 +131,7 @@ pub fn encrypt( /// /// # Examples ///```rust -/// # use rosenpass_ciphers::subtle::xchacha20poly1305_ietf::{decrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; +/// # use rosenpass_ciphers::subtle::rust_crypto::xchacha20poly1305_ietf::{decrypt, TAG_LEN, KEY_LEN, NONCE_LEN}; /// let ciphertext: &[u8] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /// # 0, 0, 0, 0, 8, 241, 229, 253, 200, 81, 248, 30, 183, 149, 134, 168, 149, 87, 109, 49, 159, 108, /// # 206, 89, 51, 232, 232, 197, 163, 253, 254, 208, 73, 76, 253, 13, 247, 162, 133, 184, 177, 44, @@ -80,8 +140,8 @@ pub fn encrypt( /// const PLAINTEXT_LEN: usize = 43; /// assert_eq!(PLAINTEXT_LEN + TAG_LEN + NONCE_LEN, ciphertext.len()); /// -/// let key: &[u8] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY -/// let nonce: &[u8] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE +/// let key: &[u8; KEY_LEN] = &[0u8; KEY_LEN]; // THIS IS NOT A SECURE KEY +/// let nonce: &[u8; NONCE_LEN] = &[0u8; NONCE_LEN]; // THIS IS NOT A SECURE NONCE /// let additional_data: &[u8] = "the encrypted message is very important".as_bytes(); /// let mut plaintext_buffer = [0u8; PLAINTEXT_LEN]; /// @@ -94,15 +154,11 @@ pub fn encrypt( #[inline] pub fn decrypt( plaintext: &mut [u8], - key: &[u8], + key: &[u8; KEY_LEN], ad: &[u8], ciphertext: &[u8], ) -> anyhow::Result<()> { - let (n, ct_mac) = ciphertext.split_at(NONCE_LEN); - let (ct, mac) = ct_mac.split_at(ct_mac.len() - TAG_LEN); - let nonce = GenericArray::from_slice(n); - let tag = GenericArray::from_slice(mac); - copy_slice(ct).to(plaintext); - AeadImpl::new_from_slice(key)?.decrypt_in_place_detached(nonce, ad, plaintext, tag)?; - Ok(()) + XChaCha20Poly1305 + .decrypt_with_nonce_in_ctxt(plaintext, key, ad, ciphertext) + .map_err(anyhow::Error::from) } diff --git a/constant-time/Cargo.toml b/constant-time/Cargo.toml index b012a41b..d9683874 100644 --- a/constant-time/Cargo.toml +++ b/constant-time/Cargo.toml @@ -8,6 +8,7 @@ description = "Rosenpass internal utilities for constant time crypto implementat homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -19,7 +20,7 @@ rosenpass-to = { workspace = true } memsec = { workspace = true } [dev-dependencies] -rand = "0.8.5" +rand = { workspace = true } [lints.rust] unexpected_cfgs = { level = "allow", check-cfg = ['cfg(coverage)'] } diff --git a/constant-time/src/memcmp.rs b/constant-time/src/memcmp.rs index 1df87094..2f72a089 100644 --- a/constant-time/src/memcmp.rs +++ b/constant-time/src/memcmp.rs @@ -32,6 +32,8 @@ pub fn memcmp(a: &[u8], b: &[u8]) -> bool { /// For discussion on how to (further) ensure the constant-time execution of this function, /// see #[cfg(all(test, feature = "constant_time_tests"))] +// Stopgap measure against https://github.com/rosenpass/rosenpass/issues/634 +#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] mod tests { use super::*; use core::hint::black_box; diff --git a/deny.toml b/deny.toml index 273109f1..794f7ee3 100644 --- a/deny.toml +++ b/deny.toml @@ -24,8 +24,7 @@ feature-depth = 1 [advisories] # A list of advisory IDs to ignore. Note that ignored advisories will still # output a note when they are encountered. -ignore = [ -] +ignore = ["RUSTSEC-2024-0370", "RUSTSEC-2024-0436", "RUSTSEC-2023-0089"] # If this is true, then cargo deny will use the git executable to fetch advisory database. # If this is false, then it uses a built-in git library. # Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support. @@ -40,11 +39,11 @@ ignore = [ # See https://spdx.org/licenses/ for list of possible licenses # [possible values: any SPDX 3.11 short identifier (+ optional exception)]. allow = [ - "MIT", - "Apache-2.0", - "Apache-2.0 WITH LLVM-exception", - "BSD-3-Clause", - "ISC", + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-3-Clause", + "ISC", ] # The confidence threshold for detecting a license from license text. # The higher the value, the more closely the license text must be to the @@ -54,9 +53,11 @@ confidence-threshold = 0.8 # Allow 1 or more licenses on a per-crate basis, so that particular licenses # aren't accepted for every possible crate as with the normal allow list exceptions = [ - # Each entry is the crate and version constraint, and its specific allow - # list - { allow = ["Unicode-DFS-2016"], crate = "unicode-ident" }, + # Each entry is the crate and version constraint, and its specific allow + # list + { allow = ["Unicode-DFS-2016", "Unicode-3.0"], crate = "unicode-ident" }, + { allow = ["NCSA"], crate = "libfuzzer-sys" }, + ] [licenses.private] @@ -89,15 +90,11 @@ workspace-default-features = "allow" # on a crate-by-crate basis if desired. external-default-features = "allow" # List of crates that are allowed. Use with care! -allow = [ -] +allow = [] # List of crates to deny -deny = [ -] +deny = [] -skip-tree = [ - -] +skip-tree = [] # This section is considered when running `cargo deny check sources`. # More documentation about the 'sources' section can be found here: diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 00000000..838c2d99 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,45 @@ +# syntax=docker/dockerfile:1 + +ARG BASE_IMAGE=debian:bookworm-slim + +# Stage 1: Base image with cargo-chef installed +FROM rust:latest AS chef +RUN cargo install cargo-chef +# install software required for liboqs-rust +RUN apt-get update && apt-get install -y clang cmake && rm -rf /var/lib/apt/lists/* + +# Stage 2: Prepare the cargo-chef recipe +FROM chef AS planner +WORKDIR /app +COPY . . +RUN cargo chef prepare --recipe-path recipe.json + +# Stage 3: Cache dependencies using the recipe +FROM chef AS cacher +WORKDIR /app +COPY --from=planner /app/recipe.json recipe.json +RUN cargo chef cook --release --recipe-path recipe.json + +# Stage 4: Build the application +FROM cacher AS builder +WORKDIR /app +COPY . . +RUN cargo build --release + +# Stage 5: Install runtime-dependencies in the base image +FROM ${BASE_IMAGE} AS base_image_with_dependencies + +RUN apt-get update && apt-get install -y iproute2 && rm -rf /var/lib/apt/lists/* + +# Final Stage (rosenpass): Copy the rosenpass binary +FROM base_image_with_dependencies AS rosenpass +COPY --from=builder /app/target/release/rosenpass /usr/local/bin/rosenpass +ENTRYPOINT [ "/usr/local/bin/rosenpass" ] + +# Final Stage (rp): Copy the rp binary +FROM base_image_with_dependencies AS rp + +RUN apt-get update && apt-get install -y wireguard && rm -rf /var/lib/apt/lists/* + +COPY --from=builder /app/target/release/rp /usr/local/bin/rp +ENTRYPOINT [ "/usr/local/bin/rp" ] diff --git a/docker/USAGE.md b/docker/USAGE.md new file mode 100644 index 00000000..5be4409c --- /dev/null +++ b/docker/USAGE.md @@ -0,0 +1,203 @@ +# Rosenpass in Docker + +Rosenpass provides post-quantum-secure key exchange for VPNs. It generates symmetric keys used by [WireGuard](https://www.wireguard.com/papers/wireguard.pdf) or other applications. The protocol enhances "Post-Quantum WireGuard" ([PQWG](https://eprint.iacr.org/2020/379)) with a cookie mechanism for better security against state disruption attacks. + +Prebuilt Docker images are available for easy deployment: + +- [`ghcr.io/rosenpass/rosenpass`](https://github.com/rosenpass/rosenpass/pkgs/container/rosenpass) – the core key exchange tool +- [`ghcr.io/rosenpass/rp`](https://github.com/rosenpass/rosenpass/pkgs/container/rp) – a frontend for setting up WireGuard VPNs + +The entrypoint of the `rosenpass` image is the `rosenpass` executable, whose documentation can be found [here](https://rosenpass.eu/docs/rosenpass-tool/manuals/rp_manual/). +Similarly, the entrypoint of the `rp` image is the `rp` executable, with its documentation available [here](https://rosenpass.eu/docs/rosenpass-tool/manuals/rp1/). + +## Usage - Standalone Key Exchange + +The `ghcr.io/rosenpass/rosenpass` image can be used in a server-client setup to exchange quantum-secure shared keys. +This setup uses rosenpass as a standalone application, without using any other component such as wireguard. +What follows, is a simple setup for illustrative purposes. + +Create a docker network that is used to connect the containers: + +```bash +docker network create -d bridge rp +export NET=rp +``` + +Generate the server and client key pairs: + +```bash +mkdir ./workdir-client ./workdir-server +docker run -it --rm -v ./workdir-server:/workdir ghcr.io/rosenpass/rosenpass \ + gen-keys --public-key=workdir/server-public --secret-key=workdir/server-secret +docker run -it --rm -v ./workdir-client:/workdir ghcr.io/rosenpass/rosenpass \ + gen-keys --public-key=workdir/client-public --secret-key=workdir/client-secret +# share the public keys between client and server + cp workdir-client/client-public workdir-server/client-public + cp workdir-server/server-public workdir-client/server-public +``` + +Start the server container: + +```bash +docker run --name "rpserver" --network ${NET} \ + -it --rm -v ./workdir-server:/workdir ghcr.io/rosenpass/rosenpass \ + exchange \ + private-key workdir/server-secret \ + public-key workdir/server-public \ + listen 0.0.0.0:9999 \ + peer public-key workdir/client-public \ + outfile workdir/server-sharedkey +``` + +Find out the ip address of the server container: + +```bash +EP="rpserver" +EP=$(docker inspect --format '{{ .NetworkSettings.Networks.rp.IPAddress }}' $EP) +``` + +Run the client container and perform the key exchange: + +```bash +docker run --name "rpclient" --network ${NET} \ + -it --rm -v ./workdir-client:/workdir ghcr.io/rosenpass/rosenpass \ + exchange \ + private-key workdir/client-secret \ + public-key workdir/client-public \ + peer public-key workdir/server-public endpoint ${EP}:9999 \ + outfile workdir/client-sharedkey +``` + +Now the containers will exchange shared keys and each put them into their respective outfile. + +Comparing the outfiles shows that these shared keys equal: + +```bash +cmp workdir-server/server-sharedkey workdir-client/client-sharedkey +``` + +It is now possible to set add these keys as pre-shared keys within a wireguard interface. +For example as the server, + +```bash +PREKEY=$(cat workdir-server/server-sharedkey) +wg set peer preshared-key <(echo "$PREKEY") +``` + +## Usage - Combined with wireguard + +The `ghcr.io/rosenpass/rp` image can be used to build a VPN with WireGuard and Rosenpass. +In this example, we run two containers on the same system and connect them with a bridge network within the docker overlay network. + +Create the named docker network, to be able to connect the containers. + +Create a docker network that is used to connect the containers: + +```bash +docker network create -d bridge rp +export NET=rp +``` + +Generate the server and client secret keys and extract public keys. + +```bash +mkdir -p ./workdir-server ./workdir-client + +# server +docker run -it --rm -v ./workdir-server:/workdir ghcr.io/rosenpass/rp \ + genkey workdir/server.rosenpass-secret +docker run -it --rm -v ./workdir-server:/workdir ghcr.io/rosenpass/rp \ + pubkey workdir/server.rosenpass-secret workdir/server.rosenpass-public + +# client +docker run -it --rm -v ./workdir-client:/workdir ghcr.io/rosenpass/rp \ + genkey workdir/client.rosenpass-secret +docker run -it --rm -v ./workdir-client:/workdir ghcr.io/rosenpass/rp \ + pubkey workdir/client.rosenpass-secret workdir/client.rosenpass-public + +# share the public keys between client and server +cp -r workdir-client/client.rosenpass-public workdir-server/client.rosenpass-public +cp -r workdir-server/server.rosenpass-public workdir-client/server.rosenpass-public +``` + +Start the server container. +Note that the `NET_ADMIN` capability is neccessary, the rp command will create and manage wireguard interfaces. +Also make sure the `wireguard` kernel module is loaded by the host. (`lsmod | grep wireguard`) + +```bash +docker run --name "rpserver" --network ${NET} -it -d --rm -v ./workdir-server:/workdir \ + --cap-add=NET_ADMIN \ + ghcr.io/rosenpass/rp \ + exchange workdir/server.rosenpass-secret dev rosenpass0 \ + listen 0.0.0.0:9999 peer workdir/client.rosenpass-public allowed-ips 10.0.0.0/8 +``` + +Now find out the ip-address of the server container and then start the client container: + +```bash +EP="rpserver" +EP=$(docker inspect --format '{{ .NetworkSettings.Networks.rp.IPAddress }}' $EP) +docker run --name "rpclient" --network ${NET} -it -d --rm -v ./workdir-client:/workdir \ + --cap-add=NET_ADMIN \ + ghcr.io/rosenpass/rp \ + exchange workdir/client.rosenpass-secret dev rosenpass1 \ + peer workdir/server.rosenpass-public endpoint ${EP}:9999 allowed-ips 10.0.0.1 +``` + +Inside the docker containers assign the IP addresses: + +```bash +# server +docker exec -it rpserver ip a add 10.0.0.1/24 dev rosenpass0 + +# client +docker exec -it rpclient ip a add 10.0.0.2/24 dev rosenpass1 +``` + +Done! The two containers should now be connected through a wireguard VPN (Port 1000) with pre-shared keys exchanged by rosenpass (Port 9999). + +Now, test the connection by starting a shell inside the client container, and ping the server through the VPN: + +```bash +# client +docker exec -it rpclient bash +apt update; apt install iputils-ping +ping 10.0.0.1 +``` + +The ping command should continuously show ping-logs: + +``` +PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data. +64 bytes from 10.0.0.1: icmp_seq=1 ttl=64 time=0.119 ms +64 bytes from 10.0.0.1: icmp_seq=2 ttl=64 time=0.132 ms +64 bytes from 10.0.0.1: icmp_seq=3 ttl=64 time=0.394 ms +... +``` + +While the ping is running, you may stop the server container, and verify that the ping-log halts. In another terminal do: + +``` +docker stop -t 1 rpserver +``` + +## Building the Docker Images Locally + +Clone the Rosenpass repository: + +``` +git clone https://github.com/rosenpass/rosenpass +cd rosenpass +``` + +Build the rp image from the root of the repository as follows: + +``` +docker build -f docker/Dockerfile -t ghcr.io/rosenpass/rp --target rp . +``` + +Build the rosenpass image from the root of the repostiry with the following command: + +``` +docker build -f docker/Dockerfile -t ghcr.io/rosenpass/rosenpass --target rosenpass . +``` diff --git a/flake.lock b/flake.lock index 06183ae0..a9dacb80 100644 --- a/flake.lock +++ b/flake.lock @@ -1,26 +1,5 @@ { "nodes": { - "fenix": { - "inputs": { - "nixpkgs": [ - "nixpkgs" - ], - "rust-analyzer-src": "rust-analyzer-src" - }, - "locked": { - "lastModified": 1728282832, - "narHash": "sha256-I7AbcwGggf+CHqpyd/9PiAjpIBGTGx5woYHqtwxaV7I=", - "owner": "nix-community", - "repo": "fenix", - "rev": "1ec71be1f4b8f3105c5d38da339cb061fefc43f4", - "type": "github" - }, - "original": { - "owner": "nix-community", - "repo": "fenix", - "type": "github" - } - }, "flake-utils": { "inputs": { "systems": "systems" @@ -39,6 +18,26 @@ "type": "github" } }, + "nix-vm-test": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1734355073, + "narHash": "sha256-FfdPOGy1zElTwKzjgIMp5K2D3gfPn6VWjVa4MJ9L1Tc=", + "owner": "numtide", + "repo": "nix-vm-test", + "rev": "5948de39a616f2261dbbf4b6f25cbe1cbefd788c", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "nix-vm-test", + "type": "github" + } + }, "nixpkgs": { "locked": { "lastModified": 1728193676, @@ -57,25 +56,30 @@ }, "root": { "inputs": { - "fenix": "fenix", "flake-utils": "flake-utils", - "nixpkgs": "nixpkgs" + "nix-vm-test": "nix-vm-test", + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay", + "treefmt-nix": "treefmt-nix" } }, - "rust-analyzer-src": { - "flake": false, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, "locked": { - "lastModified": 1728249780, - "narHash": "sha256-J269DvCI5dzBmPrXhAAtj566qt0b22TJtF3TIK+tMsI=", - "owner": "rust-lang", - "repo": "rust-analyzer", - "rev": "2b750da1a1a2c1d2c70896108d7096089842d877", + "lastModified": 1744513456, + "narHash": "sha256-NLVluTmK8d01Iz+WyarQhwFcXpHEwU7m5hH3YQQFJS0=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "730fd8e82799219754418483fabe1844262fd1e2", "type": "github" }, "original": { - "owner": "rust-lang", - "ref": "nightly", - "repo": "rust-analyzer", + "owner": "oxalica", + "repo": "rust-overlay", "type": "github" } }, @@ -93,6 +97,26 @@ "repo": "default", "type": "github" } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1743748085, + "narHash": "sha256-uhjnlaVTWo5iD3LXics1rp9gaKgDRQj6660+gbUU3cE=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "815e4121d6a5d504c0f96e5be2dd7f871e4fd99d", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } } }, "root": "root", diff --git a/flake.nix b/flake.nix index 658b06ea..9e2a9350 100644 --- a/flake.nix +++ b/flake.nix @@ -3,37 +3,51 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05"; flake-utils.url = "github:numtide/flake-utils"; + nix-vm-test.url = "github:numtide/nix-vm-test"; + nix-vm-test.inputs.nixpkgs.follows = "nixpkgs"; + nix-vm-test.inputs.flake-utils.follows = "flake-utils"; + # for rust nightly with llvm-tools-preview - fenix.url = "github:nix-community/fenix"; - fenix.inputs.nixpkgs.follows = "nixpkgs"; + rust-overlay.url = "github:oxalica/rust-overlay"; + rust-overlay.inputs.nixpkgs.follows = "nixpkgs"; + + treefmt-nix.url = "github:numtide/treefmt-nix"; + treefmt-nix.inputs.nixpkgs.follows = "nixpkgs"; }; - outputs = { self, nixpkgs, flake-utils, ... }@inputs: + outputs = + { + self, + nixpkgs, + flake-utils, + nix-vm-test, + rust-overlay, + treefmt-nix, + ... + }@inputs: nixpkgs.lib.foldl (a: b: nixpkgs.lib.recursiveUpdate a b) { } [ - # ### Export the overlay.nix from this flake ### # - { - overlays.default = import ./overlay.nix; - } - + { overlays.default = import ./overlay.nix; } # ### Actual Rosenpass Package and Docker Container Images ### # - (flake-utils.lib.eachSystem [ - "x86_64-linux" - "aarch64-linux" + (flake-utils.lib.eachSystem + [ + "x86_64-linux" + "aarch64-linux" - # unsuported best-effort - "i686-linux" - "x86_64-darwin" - "aarch64-darwin" - # "x86_64-windows" - ] - (system: + # unsuported best-effort + "i686-linux" + "x86_64-darwin" + "aarch64-darwin" + # "x86_64-windows" + ] + ( + system: let # normal nixpkgs pkgs = import nixpkgs { @@ -44,116 +58,159 @@ }; in { - packages = { - default = pkgs.rosenpass; - rosenpass = pkgs.rosenpass; - rosenpass-oci-image = pkgs.rosenpass-oci-image; - rp = pkgs.rp; + packages = + { + default = pkgs.rosenpass; + rosenpass = pkgs.rosenpass; + rosenpass-oci-image = pkgs.rosenpass-oci-image; + rp = pkgs.rp; - release-package = pkgs.release-package; + release-package = pkgs.release-package; - # for good measure, we also offer to cross compile to Linux on Arm - aarch64-linux-rosenpass-static = - pkgs.pkgsCross.aarch64-multiplatform.pkgsStatic.rosenpass; - aarch64-linux-rp-static = pkgs.pkgsCross.aarch64-multiplatform.pkgsStatic.rp; - } - // - # We only offer static builds for linux, as this is not supported on OS X - (nixpkgs.lib.attrsets.optionalAttrs pkgs.stdenv.isLinux { - rosenpass-static = pkgs.pkgsStatic.rosenpass; - rosenpass-static-oci-image = pkgs.pkgsStatic.rosenpass-oci-image; - rp-static = pkgs.pkgsStatic.rp; - }); + # for good measure, we also offer to cross compile to Linux on Arm + aarch64-linux-rosenpass-static = pkgs.pkgsCross.aarch64-multiplatform.pkgsStatic.rosenpass; + aarch64-linux-rp-static = pkgs.pkgsCross.aarch64-multiplatform.pkgsStatic.rp; + } + // + # We only offer static builds for linux, as this is not supported on OS X + (nixpkgs.lib.attrsets.optionalAttrs pkgs.stdenv.isLinux { + rosenpass-static = pkgs.pkgsStatic.rosenpass; + rosenpass-static-oci-image = pkgs.pkgsStatic.rosenpass-oci-image; + rp-static = pkgs.pkgsStatic.rp; + }); } - )) - + ) + ) # ### Linux specifics ### # - (flake-utils.lib.eachSystem [ "x86_64-linux" "aarch64-linux" ] (system: - let - pkgs = import nixpkgs { - inherit system; + (flake-utils.lib.eachSystem + [ + "x86_64-linux" + "aarch64-linux" + "i686-linux" + ] + ( + system: + let + pkgs = import nixpkgs { + inherit system; - # apply our own overlay, overriding/inserting our packages as defined in ./pkgs - overlays = [ self.overlays.default ]; - }; - in - { + overlays = [ + # apply our own overlay, overriding/inserting our packages as defined in ./pkgs + self.overlays.default - # - ### Reading materials ### - # - packages.whitepaper = pkgs.whitepaper; + nix-vm-test.overlays.default - # - ### Proof and Proof Tools ### - # - packages.proverif-patched = pkgs.proverif-patched; - packages.proof-proverif = pkgs.proof-proverif; + # apply rust-overlay to get specific versions of the rust toolchain for a MSRV check + (import rust-overlay) + ]; + }; + treefmtEval = treefmt-nix.lib.evalModule pkgs ./treefmt.nix; + in + { + packages.package-deb = pkgs.callPackage ./pkgs/package-deb.nix { + rosenpass = pkgs.pkgsStatic.rosenpass; + }; + packages.package-rpm = pkgs.callPackage ./pkgs/package-rpm.nix { + rosenpass = pkgs.pkgsStatic.rosenpass; + }; - # - ### Devshells ### - # - devShells.default = pkgs.mkShell { - inherit (pkgs.proof-proverif) CRYPTOVERIF_LIB; - inputsFrom = [ pkgs.rosenpass ]; - nativeBuildInputs = with pkgs; [ - cargo-release - clippy - rustfmt - nodePackages.prettier - nushell # for the .ci/gen-workflow-files.nu script - proverif-patched - ]; - }; - # TODO: Write this as a patched version of the default environment - devShells.fullEnv = pkgs.mkShell { - inherit (pkgs.proof-proverif) CRYPTOVERIF_LIB; - inputsFrom = [ pkgs.rosenpass ]; - nativeBuildInputs = with pkgs; [ - cargo-audit - cargo-release - rustfmt - nodePackages.prettier - nushell # for the .ci/gen-workflow-files.nu script - proverif-patched - inputs.fenix.packages.${system}.complete.toolchain - pkgs.cargo-llvm-cov - pkgs.grcov - ]; - }; - devShells.coverage = pkgs.mkShell { - inputsFrom = [ pkgs.rosenpass ]; - nativeBuildInputs = [ - inputs.fenix.packages.${system}.complete.toolchain - pkgs.cargo-llvm-cov - pkgs.grcov - ]; - }; + # + ### Reading materials ### + # + packages.whitepaper = pkgs.whitepaper; + # + ### Proof and Proof Tools ### + # + packages.proverif-patched = pkgs.proverif-patched; + packages.proof-proverif = pkgs.proof-proverif; - checks = { - systemd-rosenpass = pkgs.testers.runNixOSTest ./tests/systemd/rosenpass.nix; - systemd-rp = pkgs.testers.runNixOSTest ./tests/systemd/rp.nix; + # + ### Devshells ### + # + devShells.default = pkgs.mkShell { + inherit (pkgs.proof-proverif) CRYPTOVERIF_LIB; + inputsFrom = [ pkgs.rosenpass ]; + nativeBuildInputs = with pkgs; [ + cargo-release + clippy + rustfmt + nodePackages.prettier + nushell # for the .ci/gen-workflow-files.nu script + proverif-patched + ]; + }; + # TODO: Write this as a patched version of the default environment + devShells.fullEnv = pkgs.mkShell { + inherit (pkgs.proof-proverif) CRYPTOVERIF_LIB; + inputsFrom = [ pkgs.rosenpass ]; + nativeBuildInputs = with pkgs; [ + cargo-audit + cargo-msrv + cargo-release + cargo-vet + rustfmt + nodePackages.prettier + nushell # for the .ci/gen-workflow-files.nu script + proverif-patched + pkgs.cargo-llvm-cov + pkgs.grcov + pkgs.rust-bin.stable.latest.complete + ]; + }; + devShells.coverage = pkgs.mkShell { + inputsFrom = [ pkgs.rosenpass ]; + nativeBuildInputs = [ + pkgs.cargo-llvm-cov + pkgs.grcov + pkgs.rustc.llvmPackages.llvm + ]; + env = { + inherit (pkgs.cargo-llvm-cov) LLVM_COV LLVM_PROFDATA; + }; + }; + devShells.benchmarks = pkgs.mkShell { + inputsFrom = [ pkgs.rosenpass ]; + nativeBuildInputs = with pkgs; [ + cargo-release + clippy + rustfmt + ]; + }; - cargo-fmt = pkgs.runCommand "check-cargo-fmt" - { inherit (self.devShells.${system}.default) nativeBuildInputs buildInputs; } '' - cargo fmt --manifest-path=${./.}/Cargo.toml --check --all && touch $out - ''; - nixpkgs-fmt = pkgs.runCommand "check-nixpkgs-fmt" - { nativeBuildInputs = [ pkgs.nixpkgs-fmt ]; } '' - nixpkgs-fmt --check ${./.} && touch $out - ''; - prettier-check = pkgs.runCommand "check-with-prettier" - { nativeBuildInputs = [ pkgs.nodePackages.prettier ]; } '' - cd ${./.} && prettier --check . && touch $out - ''; - }; + checks = + { + systemd-rosenpass = pkgs.testers.runNixOSTest ./tests/systemd/rosenpass.nix; + systemd-rp = pkgs.testers.runNixOSTest ./tests/systemd/rp.nix; + formatting = treefmtEval.config.build.check self; + rosenpass-msrv-check = + let + rosenpassCargoToml = pkgs.lib.trivial.importTOML ./rosenpass/Cargo.toml; - formatter = pkgs.nixpkgs-fmt; - })) + rustToolchain = pkgs.rust-bin.stable.${rosenpassCargoToml.package.rust-version}.default; + rustPlatform = pkgs.makeRustPlatform { + cargo = rustToolchain; + rustc = rustToolchain; + }; + in + pkgs.rosenpass.override { inherit rustPlatform; }; + } + // pkgs.lib.optionalAttrs (system == "x86_64-linux") ( + import ./tests/legacy-distro-packaging.nix { + inherit pkgs; + rosenpass-deb = self.packages.${system}.package-deb; + rosenpass-rpm = self.packages.${system}.package-rpm; + } + ); + + # for `nix fmt` + formatter = treefmtEval.config.build.wrapper; + } + ) + ) ]; } diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index f8ac42fb..f22ff9cc 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -3,9 +3,10 @@ name = "rosenpass-fuzzing" version = "0.0.1" publish = false edition = "2021" +rust-version = "1.77.0" [features] -experiment_libcrux = ["rosenpass-ciphers/experiment_libcrux"] +experiment_libcrux = ["rosenpass-ciphers/experiment_libcrux_all"] [package.metadata] cargo-fuzz = true diff --git a/fuzz/fuzz_targets/aead_enc_into.rs b/fuzz/fuzz_targets/aead_enc_into.rs index 8f529f7a..89c191d1 100644 --- a/fuzz/fuzz_targets/aead_enc_into.rs +++ b/fuzz/fuzz_targets/aead_enc_into.rs @@ -4,7 +4,8 @@ extern crate rosenpass; use libfuzzer_sys::fuzz_target; -use rosenpass_ciphers::aead; +use rosenpass_cipher_traits::primitives::Aead as _; +use rosenpass_ciphers::Aead; #[derive(arbitrary::Arbitrary, Debug)] pub struct Input { @@ -17,7 +18,7 @@ pub struct Input { fuzz_target!(|input: Input| { let mut ciphertext = vec![0u8; input.plaintext.len() + 16]; - aead::encrypt( + Aead.encrypt( ciphertext.as_mut_slice(), &input.key, &input.nonce, diff --git a/fuzz/fuzz_targets/blake2b.rs b/fuzz/fuzz_targets/blake2b.rs index f4349b01..a6b41edf 100644 --- a/fuzz/fuzz_targets/blake2b.rs +++ b/fuzz/fuzz_targets/blake2b.rs @@ -4,6 +4,7 @@ extern crate rosenpass; use libfuzzer_sys::fuzz_target; +use rosenpass_cipher_traits::primitives::KeyedHashTo; use rosenpass_ciphers::subtle::blake2b; use rosenpass_to::To; @@ -16,5 +17,7 @@ pub struct Blake2b { fuzz_target!(|input: Blake2b| { let mut out = [0u8; 32]; - blake2b::hash(&input.key, &input.data).to(&mut out).unwrap(); + blake2b::Blake2b::keyed_hash_to(&input.key, &input.data) + .to(&mut out) + .unwrap(); }); diff --git a/fuzz/fuzz_targets/handle_msg.rs b/fuzz/fuzz_targets/handle_msg.rs index 6423fe7e..0bfbaa25 100644 --- a/fuzz/fuzz_targets/handle_msg.rs +++ b/fuzz/fuzz_targets/handle_msg.rs @@ -4,8 +4,8 @@ extern crate rosenpass; use libfuzzer_sys::fuzz_target; use rosenpass::protocol::CryptoServer; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; use rosenpass_secret_memory::policy::*; use rosenpass_secret_memory::{PublicBox, Secret}; use std::sync::Once; diff --git a/fuzz/fuzz_targets/kyber_encaps.rs b/fuzz/fuzz_targets/kyber_encaps.rs index 6a342f35..723003c9 100644 --- a/fuzz/fuzz_targets/kyber_encaps.rs +++ b/fuzz/fuzz_targets/kyber_encaps.rs @@ -4,8 +4,8 @@ extern crate rosenpass; use libfuzzer_sys::fuzz_target; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::EphemeralKem; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::EphemeralKem; #[derive(arbitrary::Arbitrary, Debug)] pub struct Input { @@ -16,5 +16,7 @@ fuzz_target!(|input: Input| { let mut ciphertext = [0u8; EphemeralKem::CT_LEN]; let mut shared_secret = [0u8; EphemeralKem::SHK_LEN]; - EphemeralKem::encaps(&mut shared_secret, &mut ciphertext, &input.pk).unwrap(); + EphemeralKem + .encaps(&mut shared_secret, &mut ciphertext, &input.pk) + .unwrap(); }); diff --git a/fuzz/fuzz_targets/mceliece_encaps.rs b/fuzz/fuzz_targets/mceliece_encaps.rs index ad66a6e4..bbca4568 100644 --- a/fuzz/fuzz_targets/mceliece_encaps.rs +++ b/fuzz/fuzz_targets/mceliece_encaps.rs @@ -3,13 +3,13 @@ extern crate rosenpass; use libfuzzer_sys::fuzz_target; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; fuzz_target!(|input: [u8; StaticKem::PK_LEN]| { let mut ciphertext = [0u8; StaticKem::CT_LEN]; let mut shared_secret = [0u8; StaticKem::SHK_LEN]; // We expect errors while fuzzing therefore we do not check the result. - let _ = StaticKem::encaps(&mut shared_secret, &mut ciphertext, &input); + let _ = StaticKem.encaps(&mut shared_secret, &mut ciphertext, &input); }); diff --git a/oqs/Cargo.toml b/oqs/Cargo.toml index 6a69563b..20fe2ebf 100644 --- a/oqs/Cargo.toml +++ b/oqs/Cargo.toml @@ -8,6 +8,7 @@ description = "Rosenpass internal bindings to liboqs" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [dependencies] rosenpass-cipher-traits = { workspace = true } diff --git a/oqs/src/kem_macro.rs b/oqs/src/kem_macro.rs index fc05b4f7..9117dd77 100644 --- a/oqs/src/kem_macro.rs +++ b/oqs/src/kem_macro.rs @@ -2,11 +2,10 @@ /// Generate bindings to a liboqs-provided KEM macro_rules! oqs_kem { - ($name:ident) => { ::paste::paste!{ + ($name:ident, $algo_trait:path) => { ::paste::paste!{ #[doc = "Bindings for ::oqs_sys::kem::" [<"OQS_KEM" _ $name:snake>] "_*"] mod [< $name:snake >] { - use rosenpass_cipher_traits::Kem; - use rosenpass_util::result::Guaranteed; + use rosenpass_cipher_traits::primitives::{Kem, KemError}; #[doc = "Bindings for ::oqs_sys::kem::" [<"OQS_KEM" _ $name:snake>] "_*"] #[doc = ""] @@ -14,7 +13,7 @@ macro_rules! oqs_kem { #[doc = ""] #[doc = "```rust"] #[doc = "use std::borrow::{Borrow, BorrowMut};"] - #[doc = "use rosenpass_cipher_traits::Kem;"] + #[doc = "use rosenpass_cipher_traits::primitives::Kem;"] #[doc = "use rosenpass_oqs::" $name:camel " as MyKem;"] #[doc = "use rosenpass_secret_memory::{Secret, Public};"] #[doc = ""] @@ -23,21 +22,26 @@ macro_rules! oqs_kem { #[doc = "// Recipient generates secret key, transfers pk to sender"] #[doc = "let mut sk = Secret::<{ MyKem::SK_LEN }>::zero();"] #[doc = "let mut pk = Public::<{ MyKem::PK_LEN }>::zero();"] - #[doc = "MyKem::keygen(sk.secret_mut(), pk.borrow_mut());"] + #[doc = "MyKem.keygen(sk.secret_mut(), &mut pk);"] #[doc = ""] #[doc = "// Sender generates ciphertext and local shared key, sends ciphertext to recipient"] #[doc = "let mut shk_enc = Secret::<{ MyKem::SHK_LEN }>::zero();"] #[doc = "let mut ct = Public::<{ MyKem::CT_LEN }>::zero();"] - #[doc = "MyKem::encaps(shk_enc.secret_mut(), ct.borrow_mut(), pk.borrow());"] + #[doc = "MyKem.encaps(shk_enc.secret_mut(), &mut ct, &pk);"] #[doc = ""] #[doc = "// Recipient decapsulates ciphertext"] #[doc = "let mut shk_dec = Secret::<{ MyKem::SHK_LEN }>::zero();"] - #[doc = "MyKem::decaps(shk_dec.secret_mut(), sk.secret(), ct.borrow());"] + #[doc = "MyKem.decaps(shk_dec.secret_mut(), sk.secret_mut(), &ct);"] #[doc = ""] #[doc = "// Both parties end up with the same shared key"] - #[doc = "assert!(rosenpass_constant_time::compare(shk_enc.secret_mut(), shk_dec.secret_mut()) == 0);"] + #[doc = "assert!(rosenpass_constant_time::compare(shk_enc.secret(), shk_dec.secret()) == 0);"] #[doc = "```"] - pub enum [< $name:camel >] {} + pub struct [< $name:camel >]; + + pub const SK_LEN: usize = ::oqs_sys::kem::[] as usize; + pub const PK_LEN: usize = ::oqs_sys::kem::[] as usize; + pub const CT_LEN: usize = ::oqs_sys::kem::[] as usize; + pub const SHK_LEN: usize = ::oqs_sys::kem::[] as usize; /// # Panic & Safety /// @@ -51,17 +55,8 @@ macro_rules! oqs_kem { /// to only check that the buffers are big enough, allowing them to be even /// bigger. However, from a correctness point of view it does not make sense to /// allow bigger buffers. - impl Kem for [< $name:camel >] { - type Error = ::std::convert::Infallible; - - const SK_LEN: usize = ::oqs_sys::kem::[] as usize; - const PK_LEN: usize = ::oqs_sys::kem::[] as usize; - const CT_LEN: usize = ::oqs_sys::kem::[] as usize; - const SHK_LEN: usize = ::oqs_sys::kem::[] as usize; - - fn keygen(sk: &mut [u8], pk: &mut [u8]) -> Guaranteed<()> { - assert_eq!(sk.len(), Self::SK_LEN); - assert_eq!(pk.len(), Self::PK_LEN); + impl Kem for [< $name:camel >] { + fn keygen(&self, sk: &mut [u8; SK_LEN], pk: &mut [u8; PK_LEN]) -> Result<(), KemError> { unsafe { oqs_call!( ::oqs_sys::kem::[< OQS_KEM _ $name:snake _ keypair >], @@ -73,10 +68,7 @@ macro_rules! oqs_kem { Ok(()) } - fn encaps(shk: &mut [u8], ct: &mut [u8], pk: &[u8]) -> Guaranteed<()> { - assert_eq!(shk.len(), Self::SHK_LEN); - assert_eq!(ct.len(), Self::CT_LEN); - assert_eq!(pk.len(), Self::PK_LEN); + fn encaps(&self, shk: &mut [u8; SHK_LEN], ct: &mut [u8; CT_LEN], pk: &[u8; PK_LEN]) -> Result<(), KemError> { unsafe { oqs_call!( ::oqs_sys::kem::[< OQS_KEM _ $name:snake _ encaps >], @@ -89,10 +81,7 @@ macro_rules! oqs_kem { Ok(()) } - fn decaps(shk: &mut [u8], sk: &[u8], ct: &[u8]) -> Guaranteed<()> { - assert_eq!(shk.len(), Self::SHK_LEN); - assert_eq!(sk.len(), Self::SK_LEN); - assert_eq!(ct.len(), Self::CT_LEN); + fn decaps(&self, shk: &mut [u8; SHK_LEN], sk: &[u8; SK_LEN], ct: &[u8; CT_LEN]) -> Result<(), KemError> { unsafe { oqs_call!( ::oqs_sys::kem::[< OQS_KEM _ $name:snake _ decaps >], @@ -105,9 +94,16 @@ macro_rules! oqs_kem { Ok(()) } } - } + impl Default for [< $name:camel >] { + fn default() -> Self { + Self + } + } + + impl $algo_trait for [< $name:camel >] {} + pub use [< $name:snake >] :: [< $name:camel >]; }} } diff --git a/oqs/src/lib.rs b/oqs/src/lib.rs index 842a8d5d..8117c681 100644 --- a/oqs/src/lib.rs +++ b/oqs/src/lib.rs @@ -22,5 +22,8 @@ macro_rules! oqs_call { #[macro_use] mod kem_macro; -oqs_kem!(kyber_512); -oqs_kem!(classic_mceliece_460896); +oqs_kem!(kyber_512, rosenpass_cipher_traits::algorithms::KemKyber512); +oqs_kem!( + classic_mceliece_460896, + rosenpass_cipher_traits::algorithms::KemClassicMceliece460896 +); diff --git a/overlay.nix b/overlay.nix index 5e98dfcf..25505288 100644 --- a/overlay.nix +++ b/overlay.nix @@ -1,6 +1,5 @@ final: prev: { - # ### Actual rosenpass software ### # @@ -27,7 +26,10 @@ final: prev: { "marzipan(/marzipan.awk)?" "analysis(/.*)?" ]; - nativeBuildInputs = [ final.proverif final.graphviz ]; + nativeBuildInputs = [ + final.proverif + final.graphviz + ]; CRYPTOVERIF_LIB = final.proverif-patched + "/lib/cryptoverif.pvl"; installPhase = '' mkdir -p $out diff --git a/papers/graphics/rosenpass-wireguard-hybrid-security.pdf b/papers/graphics/rosenpass-wireguard-hybrid-security.pdf new file mode 100644 index 00000000..b7a8884b Binary files /dev/null and b/papers/graphics/rosenpass-wireguard-hybrid-security.pdf differ diff --git a/papers/references.bib b/papers/references.bib index 96f524a9..16e788b9 100644 --- a/papers/references.bib +++ b/papers/references.bib @@ -196,3 +196,13 @@ Vadim Lyubashevsky and John M. Schanck and Peter Schwabe and Gregor Seiler and D type = {NIST Post-Quantum Cryptography Selected Algorithm}, url = {https://pq-crystals.org/kyber/} } + + +@misc{SHAKE256, + author = "National Institute of Standards and Technology", + title = "FIPS PUB 202: SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions", + year = {2015}, + month = {August}, + doi = {10.6028/NIST.FIPS.202} +} + diff --git a/papers/tex/template-rosenpass.tex b/papers/tex/template-rosenpass.tex index d7535944..30178927 100644 --- a/papers/tex/template-rosenpass.tex +++ b/papers/tex/template-rosenpass.tex @@ -2,6 +2,7 @@ \usepackage{amssymb} \usepackage{mathtools} \usepackage{fontspec} +\usepackage{dirtytalk} %font fallback \directlua{luaotfload.add_fallback diff --git a/papers/whitepaper.md b/papers/whitepaper.md index 266dcbf6..0f81f20d 100644 --- a/papers/whitepaper.md +++ b/papers/whitepaper.md @@ -8,13 +8,15 @@ author: - Lisa Schmidt = {Scientific Illustrator – \\url{mullana.de}} - Prabhpreet Dua abstract: | - Rosenpass is used to create post-quantum-secure VPNs. Rosenpass computes a shared key, WireGuard (WG) [@wg] uses the shared key to establish a secure connection. Rosenpass can also be used without WireGuard, deriving post-quantum-secure symmetric keys for another application. The Rosenpass protocol builds on “Post-quantum WireGuard” (PQWG) [@pqwg] and improves it by using a cookie mechanism to provide security against state disruption attacks. + Rosenpass is a post-quantum-secure authenticated key exchange protocol. Its main practical use case is creating post-quantum-secure VPNs by combining WireGuard and Rosenpass. - The WireGuard implementation enjoys great trust from the cryptography community and has excellent performance characteristics. To preserve these features, the Rosenpass application runs side-by-side with WireGuard and supplies a new post-quantum-secure pre-shared key (PSK) every two minutes. WireGuard itself still performs the pre-quantum-secure key exchange and transfers any transport data with no involvement from Rosenpass at all. + In this combination, Rosenpass generates a post-quantum-secure shared key every two minutes that is then used by WireGuard (WG) [@wg] to establish a secure connection. Rosenpass can also be used without WireGuard, providing post-quantum-secure symmetric keys for other applications, as long as the other application accepts a pre-shared key and provides cryptographic security based on the pre-shared key alone. + + The Rosenpass protocol builds on “Post-quantum WireGuard” (PQWG) [@pqwg] and improves it by using a cookie mechanism to provide security against state disruption attacks. From a cryptographic perspective, Rosenpass can be thought of as a post-quantum secure variant of the Noise IK[@noise] key exchange. \say{Noise IK} means that the protocol makes both parties authenticate themselves, but that the initiator knows before the protocol starts which other party they are communicating with. There is no negotiation step where the responder communicates their identity to the initiator. The Rosenpass project consists of a protocol description, an implementation written in Rust, and a symbolic analysis of the protocol’s security using ProVerif [@proverif]. We are working on a cryptographic security proof using CryptoVerif [@cryptoverif]. - This document is a guide for engineers and researchers implementing the protocol; a scientific paper discussing the security properties of Rosenpass is work in progress. + This document is a guide for engineers and researchers implementing the protocol. --- \enlargethispage{5mm} @@ -31,10 +33,10 @@ abstract: | # Security -Rosenpass inherits most security properties from Post-Quantum WireGuard (PQWG). The security properties mentioned here are covered by the symbolic analysis in the Rosenpass repository. +Rosenpass inherits most security properties from Post-Quantum WireGuard (PQWG). The security properties mentioned here are covered by the symbolic analysis in the Rosenpass repository. ## Secrecy -Three key encapsulations using the keypairs `sski`/`spki`, `sskr`/`spkr`, and `eski`/`epki` provide secrecy (see Section \ref{variables} for an introduction of the variables). Their respective ciphertexts are called `scti`, `sctr`, and `ectr` and the resulting keys are called `spti`, `sptr`, `epti`. A single secure encapsulation is sufficient to provide secrecy. We use two different KEMs (Key Encapsulation Mechanisms; see section \ref{skem}): Kyber and Classic McEliece. +Three key encapsulations using the keypairs `sski`/`spki`, `sskr`/`spkr`, and `eski`/`epki` provide secrecy (see Section \ref{variables} for an introduction of the variables). Their respective ciphertexts are called `scti`, `sctr`, and `ectr` and the resulting keys are called `spti`, `sptr`, `epti`. A single secure encapsulation is sufficient to provide secrecy. We use two different KEMs (Key Encapsulation Mechanisms; see Section \ref{skem}): Kyber and Classic McEliece. ## Authenticity @@ -64,9 +66,12 @@ Note that while Rosenpass is secure against state disruption, using it does not All symmetric keys and hash values used in Rosenpass are 32 bytes long. -### Hash +### Hash {#hash} -A keyed hash function with one 32-byte input, one variable-size input, and one 32-byte output. As keyed hash function we use the HMAC construction [@rfc_hmac] with BLAKE2s [@rfc_blake2] as the inner hash function. +A keyed hash function with one 32-byte input, one variable-size input, and one 32-byte output. As keyed hash function we offer two options that can be configured on a peer-basis, with Blake2s being the default: + +1. the HMAC construction [@rfc_hmac] with BLAKE2s [@rfc_blake2] as the inner hash function. +2. the SHAKE256 extendable output function (XOF) [@SHAKE256] truncated to a 32-byte output. The result is produced be concatenating the 32-byte input with the variable-size input in this order. ```pseudorust hash(key, data) -> key @@ -151,16 +156,18 @@ Rosenpass uses two types of ID variables. See Figure \ref{img:HashingTree} for h The first lower-case character indicates whether the variable is a session ID (`sid`) or a peer ID (`pid`). The final character indicates the role using the characters `i`, `r`, `m`, or `t`, for `initiator`, `responder`, `mine`, or `theirs` respectively. -### Symmetric Keys - -Rosenpass uses two symmetric key variables `psk` and `osk` in its interface, and maintains the entire handshake state in a variable called the chaining key. +### Symmetric Keys {#symmetric-keys} +Rosenpass uses two main symmetric key variables `psk` and `osk` in its interface, and maintains the entire handshake state in a variable called the chaining key. * `psk`: A pre-shared key that can be optionally supplied as input to Rosenpass. -* `osk`: The output shared key, generated by Rosenpass and supplied to WireGuard for use as its pre-shared key. -* `ck`: The chaining key. +* `osk`: The output shared key, generated by Rosenpass. The main use case is to supply the key to WireGuard for use as its pre-shared key. +* `ck`: The chaining key. This refers to various intermediate keys produced during the execution of the protocol, before the final `osk` is produced. + +We mix all key material (e.g. `psk`) into the chaining key and derive symmetric keys such as `osk` from it. We authenticate public values by mixing them into the chaining key; in particular, we include the entire protocol transcript in the chaining key, i.e., all values transmitted over the network. + +The protocol allows for multiple `osk`s to be generated; each of these keys is labeled with a domain separator to make sure different key usages are always given separate keys. The domain separator for using Rosenpass and WireGuard together is a token generated using the domain separator sequence `["rosenpass.eu", "wireguard psk"]` (see Fig. \ref{img:HashingTree}), as described in \ref{protocol-extension-wireguard-psk}. Third-parties using Rosenpass-keys for other purposes are asked to define their own protocol-extensions. Standard protocol extensions are described in \ref{protocol-extensions}. -We mix all key material (e.g. `psk`) into the chaining key, and derive symmetric keys such as `osk` from it. We authenticate public values by mixing them into the chaining key; in particular, we include the entire protocol transcript in the chaining key, i.e., all values transmitted over the network. ## Hashes @@ -172,20 +179,22 @@ Rosenpass uses a cryptographic hash function for multiple purposes: * Key derivation during and after the handshake * Computing the additional data for the biscuit encryption, to provide some privacy for its contents +Recall from Section \ref{hash} that rosenpass supports using either BLAKE2s or SHAKE256 as hash function, which can be configured for each peer ID. However, as noted above, rosenpass uses a hash function to compute the peer ID and thus also to access the configuration for a peer ID. This is an issue when receiving an `InitHello`-message, because the correct hash function is not known when a responder receives this message and at the same the responders needs it in order to compute the peer ID and by that also identfy the hash function for that peer. The reference implementation resolves this issue by first trying to derive the peer ID using SHAKE256. If that does not work (i.e. leads to an AEAD decryption error), the reference implementation tries again with BLAKE2s. The reference implementation verifies that the hash function matches the one confgured for the peer. Similarly, if the correct peer ID is not cached when receiving an InitConf message, the reference implementation proceeds in the same manner. + Using one hash function for multiple purposes can cause real-world security issues and even key recovery attacks [@oraclecloning]. We choose a tree-based domain separation scheme based on a keyed hash function – the previously introduced primitive `hash` – to make sure all our hash function calls can be seen as distinct. \setupimage{landscape,fullpage,label=img:HashingTree} ![Rosenpass Hashing Tree](graphics/rosenpass-wp-hashing-tree-rgb.svg) -Each tree node $\circ{}$ in Figure 3 represents the application of the keyed hash function, using the previous chaining key value as first parameter. The root of the tree is the zero key. In level one, the `PROTOCOL` identifier is applied to the zero key to generate a label unique across cryptographic protocols (unless the same label is deliberately used elsewhere). In level two, purpose identifiers are applied to the protocol label to generate labels to use with each separate hash function application within the Rosenpass protocol. The following layers contain the inputs used in each separate usage of the hash function: Beneath the identifiers `"mac"`, `"cookie"`, `"peer id"`, and `"biscuit additional data"` are hash functions or message authentication codes with a small number of inputs. The second, third, and fourth column in Figure 3 cover the long sequential branch beneath the identifier `"chaining key init"` representing the entire protocol execution, one column for each message processed during the handshake. The leaves beneath `"chaining key extract"` in the left column represent pseudo-random labels for use when extracting values from the chaining key during the protocol execution. These values such as `mix >` appear as outputs in the left column, and then as inputs `< mix` in the other three columns. +Each tree node $\circ{}$ in Figure \ref{img:HashingTree} represents the application of the keyed hash function, using the previous chaining key value as first parameter. The root of the tree is the zero key. In level one, the `PROTOCOL` identifier is applied to the zero key to generate a label unique across cryptographic protocols (unless the same label is deliberately used elsewhere). In level two, purpose identifiers are applied to the protocol label to generate labels to use with each separate hash function application within the Rosenpass protocol. The following layers contain the inputs used in each separate usage of the hash function: Beneath the identifiers `"mac"`, `"cookie"`, `"peer id"`, and `"biscuit additional data"` are hash functions or message authentication codes with a small number of inputs. The second, third, and fourth column in Figure \ref{img:HashingTree} cover the long sequential branch beneath the identifier `"chaining key init"` representing the entire protocol execution, one column for each message processed during the handshake. The leaves beneath `"chaining key extract"` in the left column represent pseudo-random labels for use when extracting values from the chaining key during the protocol execution. These values such as `mix >` appear as outputs in the left column, and then as inputs `< mix` in the other three columns. -The protocol identifier is defined as follows: +The protocol identifier depends on the hash function used with the respective peer is defined as follows if BLAKE2s [@rfc_blake2] is used: ```pseudorust PROTOCOL = "rosenpass 1 rosenpass.eu aead=chachapoly1305 hash=blake2s ekem=kyber512 skem=mceliece460896 xaead=xchachapoly1305" ``` -Since every tree node represents a sequence of `hash` calls, the node beneath `"handshake encryption"` called `hs_enc` can be written as follows: +If SHAKE256 [@SHAKE256] is used, `blake2s` is replaced by `shake256` in `PROTOCOL`. Since every tree node represents a sequence of `hash` calls, the node beneath `"handshake encryption"` called `hs_enc` can be written as follows: ```pseudorust hs_enc = hash(hash(hash(0, PROTOCOL), "chaining key extract"), "handshake encryption") @@ -233,6 +242,7 @@ For each peer, the server stores: * `psk` – The pre-shared key used with the peer * `spkt` – The peer's public key * `biscuit_used` – The `biscuit_no` from the last biscuit accepted for the peer as part of InitConf processing +* `hash_function` – The hash function, SHAKE256 or BLAKE2s, used with the peer. ### Handshake State and Biscuits @@ -283,7 +293,7 @@ fn lookup_session(sid); The protocol framework used by Rosenpass allows arbitrarily many different keys to be extracted using labels for each key. The `extract_key` function is used to derive protocol-internal keys, its labels are under the “chaining key extract” node in Figure \ref{img:HashingTree}. The export key function is used to export application keys. -Third-party applications using the protocol are supposed to choose a unique label (e.g., their domain name) and use that as their own namespace for custom labels. The Rosenpass project itself uses the “rosenpass.eu” namespace. +Third-party applications using the protocol are supposed to define a protocol extension (see \ref{protocol-extensions}) and choose a globally unique label, such as their domain name for custom labels of their own. The Rosenpass project itself uses the `["rosenpass.eu"]` namespace in the WireGuard PSK protocol extension (see \ref{protocol-extension-wireguard-psk}). Applications can cache or statically compile the pseudo-random label values into their binary to improve performance. @@ -389,7 +399,7 @@ fn load_biscuit(nct) { // In December 2024, the InitConf retransmission mechanisim was redesigned // in a backwards-compatible way. See the changelog. - // + // // -- 2024-11-30, Karolin Varner if (protocol_version!(< "0.3.0")) { // Ensure that the biscuit is used only once @@ -415,6 +425,18 @@ fn enter_live() { txkr ← extract_key("responder payload encryption"); txnm ← 0; txnt ← 0; + + // Setup output keys for protocol extensions such as the + // WireGuard PSK protocol extension. + setup_osks(); +} +``` + +The final step `setup_osks()` can be defined by protocol extensions (see \ref{protocol-extensions}) to set up `osk`s for custom use cases. By default, the WireGuard PSK (see \ref{protocol-extension-wireguard-psk}) is active. + +```pseudorust +fn setup_osks() { + ... // Defined by protocol extensions } ``` @@ -442,24 +464,24 @@ ICR5 and ICR6 perform biscuit replay protection using the biscuit number. This i ### Denial of Service Mitigation and Cookies -Rosenpass derives its cookie-based DoS mitigation technique for a responder when receiving InitHello messages from Wireguard [@wg]. +Rosenpass derives its cookie-based DoS mitigation technique for a responder when receiving InitHello messages from Wireguard [@wg]. When the responder is under load, it may choose to not process further InitHello handshake messages, but instead to respond with a cookie reply message (see Figure \ref{img:MessageTypes}). -The sender of the exchange then uses this cookie in order to resend the message and have it accepted the following time by the reciever. +The sender of the exchange then uses this cookie in order to resend the message and have it accepted the following time by the reciever. For an initiator, Rosenpass ignores all messages when under load. #### Cookie Reply Message -The cookie reply message is sent by the responder on receiving an InitHello message when under load. It consists of the `sidi` of the initiator, a random 24-byte bitstring `nonce` and encrypting `cookie_value` into a `cookie_encrypted` reply field which consists of the following: +The cookie reply message is sent by the responder on receiving an InitHello message when under load. It consists of the `sidi` of the initiator, a random 24-byte bitstring `nonce` and encrypting `cookie_value` into a `cookie_encrypted` reply field, which consists of the following: ```pseudorust cookie_value = lhash("cookie-value", cookie_secret, initiator_host_info)[0..16] cookie_encrypted = XAEAD(lhash("cookie-key", spkm), nonce, cookie_value, mac_peer) ``` -where `cookie_secret` is a secret variable that changes every two minutes to a random value. `initiator_host_info` is used to identify the initiator host, and is implementation-specific for the client. This paramaters used to identify the host must be carefully chosen to ensure there is a unique mapping, especially when using IPv4 and IPv6 addresses to identify the host (such as taking care of IPv6 link-local addresses). `cookie_value` is a truncated 16 byte value from the above hash operation. `mac_peer` is the `mac` field of the peer's handshake message to which message is the reply. +where `cookie_secret` is a secret variable that changes every two minutes to a random value. Moreover, `lhash` is always instantiated with SHAKE256 when computing `cookie_value` for compatability reasons. `initiator_host_info` is used to identify the initiator host, and is implementation-specific for the client. This paramaters used to identify the host must be carefully chosen to ensure there is a unique mapping, especially when using IPv4 and IPv6 addresses to identify the host (such as taking care of IPv6 link-local addresses). `cookie_value` is a truncated 16 byte value from the above hash operation. `mac_peer` is the `mac` field of the peer's handshake message to which message is the reply. #### Envelope `mac` Field @@ -489,13 +511,13 @@ else { Here, `seconds_since_update(peer.cookie_value)` is the amount of time in seconds ellapsed since last cookie was received, and `COOKIE_WIRE_DATA` are the message contents of all bytes of the retransmitted message prior to the `cookie` field. The inititator can use an invalid value for the `cookie` value, when the responder is not under load, and the responder must ignore this value. -However, when the responder is under load, it may reject InitHello messages with the invalid `cookie` value, and issue a cookie reply message. +However, when the responder is under load, it may reject InitHello messages with the invalid `cookie` value, and issue a cookie reply message. ### Conditions to trigger DoS Mechanism This whitepaper does not mandate any specific mechanism to detect responder contention (also mentioned as the under load condition) that would trigger use of the cookie mechanism. -For the reference implemenation, Rosenpass has derived inspiration from the linux implementation of Wireguard. This implementation suggests that the reciever keep track of the number of messages it is processing at a given time. +For the reference implemenation, Rosenpass has derived inspiration from the Linux implementation of Wireguard. This implementation suggests that the reciever keep track of the number of messages it is processing at a given time. On receiving an incoming message, if the length of the message queue to be processed exceeds a threshold `MAX_QUEUED_INCOMING_HANDSHAKES_THRESHOLD`, the client is considered under load and its state is stored as under load. In addition, the timestamp of this instant when the client was last under load is stored. When recieving subsequent messages, if the client is still in an under load state, the client will check if the time ellpased since the client was last under load has exceeded `LAST_UNDER_LOAD_WINDOW` seconds. If this is the case, the client will update its state to normal operation, and process the message in a normal fashion. @@ -514,25 +536,181 @@ The responder uses less complex form of the same mechanism: The responder never ### Interaction with cookie reply system -The cookie reply system does not interfere with the retransmission logic discussed above. +The cookie reply system does not interfere with the retransmission logic discussed above. When the initator is under load, it will ignore processing any incoming messages. -When a responder is under load and it receives an InitHello handshake message, the InitHello message will be discarded and a cookie reply message is sent. The initiator, then on the reciept of the cookie reply message, will store a decrypted `cookie_value` to set the `cookie` field to subsequently sent messages. As per the retransmission mechanism above, the initiator will send a retransmitted InitHello message with a valid `cookie` value appended. On receiving the retransmitted handshake message, the responder will validate the `cookie` value and resume with the handshake process. +When a responder is under load and it receives an InitHello handshake message, the InitHello message will be discarded and a cookie reply message is sent. The initiator, then on the reciept of the cookie reply message, will store a decrypted `cookie_value` to set the `cookie` field to subsequently sent messages. As per the retransmission mechanism above, the initiator will send a retransmitted InitHello message with a valid `cookie` value appended. On receiving the retransmitted handshake message, the responder will validate the `cookie` value and resume with the handshake process. When the responder is under load and it recieves an InitConf message, the message will be directly processed without checking the validity of the cookie field. +# Protocol extensions {#protocol-extensions} + +The main extension point for the Rosenpass protocol is to generate `osk`s (speak output shared keys, see Sec. \ref{symmetric-keys}) for purposes other than using them to secure WireGuard. By default, the Rosenpass application generates keys for the WireGuard PSK (see \ref{protocol-extension-wireguard-psk}). It would not be impossible to use the keys generated for WireGuard in other use cases, but this might lead to attacks[@oraclecloning]. Specifying a custom protocol extension in practice just means settling on alternative domain separators (see Sec. \ref{symmetric-keys}, Fig. \ref{img:HashingTree}). + +## Using custom domain separators in the Rosenpass application + +The Rosenpass application supports protocol extensions to change the OSK domain separator without modification of the source code. + +The following example configuration file can be used to execute Rosenpass in outfile mode with custom domain separators. +In this mode, the Rosenpass application will write keys to the file specified with `key_out` and send notifications when new keys are exchanged via standard out. +This can be used to embed Rosenpass into third-party application. + +```toml +# peer-a.toml +public_key = "peer-a.pk" +secret_key = "peer-a.sk" +listen = ["[::1]:6789"] +verbosity = "Verbose" + +[[peers]] +public_key = "peer-b.pk" +key_out = "peer-a.osk" # path to store the key +osk_organization = "myorg.com" +osk_label = ["My Custom Messenger app", "Backend VPN Example Subusecase"] +``` + +## Extension: WireGuard PSK {#protocol-extension-wireguard-psk} + +The WireGuard PSK protocol extension is active by default; this is the mode where Rosenpass is used to provide post-quantum security for WireGuard. Hybrid security (i.e. redundant pre-quantum and post-quantum security) is achieved because WireGuard provides pre-quantum security, with or without Rosenpass. + +This extension uses the `"rosenpass.eu"` namespace for user-labels and specifies a single additional user-label: + +* `["rosenpass.eu", "wireguard psk"]` + +The label's full domain separator is + +* `[PROTOCOL, "user", "rosenpass.eu", "wireguard psk"]` + +and can be seen in Figure \ref{img:HashingTree}. + +We require two extra per-peer configuration variables: + +* `wireguard_interface` — Name of a local network interface. Identifies local WireGuard interface we are supplying a PSK to. +* `wireguard_peer` — A WireGuard public key. Identifies the particular WireGuard peer whose connection we are supplying PSKs for. + +When creating the WireGuard interface for use with Rosenpass, the PSK used by WireGuard must be initialized to a random value; otherwise, WireGuard can establish an insecure key before Rosenpass had a change to exchange its own key. + +```pseudorust +fn on_wireguard_setup() { + // We use a random PSK to make sure the other side will never + // have a matching PSK when the WireGuard interface is created. + // + // Never use a fixed value here as this would lead to an attack! + let fake_wireguard_psk = random_key(); + + // How the interface is create + let wg_peer = WireGuard::setup_peer() + .public_key(wireguard_peer) + ... // Supply any custom peerconfiguration + .psk(fake_wireguard_psk); + + // The random PSK must be supplied before the + // WireGuard interface comes up + WireGuard::setup_interface() + .name(wireguard_interface) + ... // Supply any custom configuration + .add_peer(wg_peer) + .create(); +} +``` + +Every time a key is successfully negotiated, we upload the key to WireGuard. +For this protocol extension, the `setup_osks()` function is thus defined as: + +```pseudorust +fn setup_osks() { + // Generate WireGuard OSK (output shared key) from Rosenpass' + // perspective, respectively the PSK (preshared key) from + // WireGuard's perspective + let wireguard_psk = export_key("rosenpass.eu", "wireguard psk"); + + /// Supply the PSK to WireGuard + WireGuard::get_interface(wireguard_interface) + .get_peer(wireguard_peer) + .set_psk(wireguard_psk); +} +``` + +The Rosenpass protocol uses key renegotiation, just like WireGuard. +If no new `osk` is produced within a set amount of time, the OSK generated by Rosenpass times out. +In this case, the WireGuard PSK must be overwritten with a random key. +This interaction is visualized in Figure \ref{img:ExtWireguardPSKHybridSecurity}. + +```pseudorust +fn on_key_timeout() { + // Generate a random – deliberately invalid – WireGuard PSK. + // Never use a fixed value here as this would lead to an attack! + let fake_wireguard_psk = random_key(); + + // Securely erase the PSK currently used by WireGuard by + // overwriting it with the fake key we just generated. + WireGuard::get_interface(wireguard_interface) + .get_peer(wireguard_peer) + .set_psk(fake_wireguard_psk); +} +``` + +\setupimage{label=img:ExtWireguardPSKHybridSecurity,fullpage} +![Rosenpass + WireGuard: Hybrid Security](graphics/rosenpass-wireguard-hybrid-security.pdf) + # Changelog ### 0.3.x +#### 2025-06-24 – Specifying the `osk` used for WireGuard as a protocol extension + +\vspace{0.5em} + +Author: Karolin varner + +PR: [#664](https://github.com/rosenpass/rosenpass/pull/664) + +\vspace{0.5em} + +We introduce the concept of protocol extensions to make the option of using Rosenpass for purposes other than encrypting WireGuard more explicit. This captures the status-quo in a better way and does not constitute a functional change of the protocol. + +When we designed the Rosenpass protocol, we built it with support for alternative `osk`-labels in mind. +This is why we specified the domain separator for the `osk` to be `[PROTOCOL, "user", "rosenpass.eu", "wireguard psk"]`. +By choosing alternative values for the namespace (e.g. `"myorg.eu"` instead of `"rosenpass.eu`) and the label (e.g. `"MyApp Symmetric Encryption"`), the protocol could easily accommodate alternative usage scenarios. + +By introducing the concept of protocol extensions, we make this possibility explicit. + +1. Reworded the abstract to make it clearer that Rosenpass can be used for other purposes than to secure WireGuard +2. Reworded Section Symmetric Keys, adding references to the new section on protocol extension +3. Added a `setup_osks()` function in section Hashes, to make the reference to protocol extensions explicit +4. Added a new section on protocol extensions and the standard extension for using Rosenpass with WireGuard +5. Added a new graphic to showcase how Rosenpass and WireGuard interact +5. Minor formatting and intra-document references fixes + +#### 2025-05-22 - SHAKE256 keyed hash +\vspace{0.5em} + +Author: David Niehues + +PR: [#653](https://github.com/rosenpass/rosenpass/pull/653) + +\vspace{0.5em} + +We document the support for SHAKE256 with prepended key as an alternative to BLAKE2s with HMAC. + +Previously, BLAKE2s with HMAC was the only supported keyed hash function. Recently, SHAKE256 was added as an option. SHAKE256 is used as a keyed hash function by prepending the key to the variable-length data and then evaluating SHAKE256. +In order to maintain compatablity without introducing an explcit version number in the protocol messages, SHAKE256 is truncated to 32 bytes. In the update to the whitepaper, we explain where and how SHAKE256 is used. That is: + +1. We explain that SHAKE256 or BLAKE2s can be configured to be used on a peer basis. +2. We explain under which circumstances, the reference implementation tries both hash functions for messages in order to determine the correct hash function. +3. We document that the cookie mechanism always uses SHAKE256. + + #### 2024-10-30 – InitConf retransmission updates \vspace{0.5em} -Author: Karolin Varner -Issue: [#331](https://github.com/rosenpass/rosenpass/issues/331) -PR: [#513](https://github.com/rosenpass/rosenpass/pull/513) +Author: Karolin Varner + +Issue: [#331](https://github.com/rosenpass/rosenpass/issues/331) + +PR: [#513](https://github.com/rosenpass/rosenpass/pull/513) \vspace{0.5em} @@ -550,7 +728,7 @@ By removing all retransmission handling code from the cryptographic protocol, we The responder does not need to do anything special to handle RespHello retransmission – if the RespHello package is lost, the initiator retransmits InitHello and the responder can generate another RespHello package from that. InitConf retransmission needs to be handled specifically in the responder code because accepting an InitConf retransmission would reset the live session including the nonce counter, which would cause nonce reuse. Implementations must detect the case that `biscuit_no = biscuit_used` in ICR5, skip execution of ICR6 and ICR7, and just transmit another EmptyData package to confirm that the initiator can stop transmitting InitConf. \end{quote} - by + by \begin{quote} The responder uses less complex form of the same mechanism: The responder never retransmits RespHello, instead the responder generates a new RespHello message if InitHello is retransmitted. Responder confirmation messages of completed handshake (EmptyData) messages are retransmitted by storing the most recent InitConf messages (or their hashes) and caching the associated EmptyData messages. Through this cache, InitConf retransmission is detected and the associated EmptyData message is retransmitted. @@ -573,7 +751,7 @@ By removing all retransmission handling code from the cryptographic protocol, we \begin{minted}{pseudorust} // In December 2024, the InitConf retransmission mechanisim was redesigned // in a backwards-compatible way. See the changelog. - // + // // -- 2024-11-30, Karolin Varner if (protocol_version!(< "0.3.0")) { // Ensure that the biscuit is used only once @@ -587,9 +765,11 @@ By removing all retransmission handling code from the cryptographic protocol, we \vspace{0.5em} -Author: Prabhpreet Dua -Issue: [#137](https://github.com/rosenpass/rosenpass/issues/137) -PR: [#142](https://github.com/rosenpass/rosenpass/pull/142) +Author: Prabhpreet Dua + +Issue: [#137](https://github.com/rosenpass/rosenpass/issues/137) + +PR: [#142](https://github.com/rosenpass/rosenpass/pull/142) \vspace{0.5em} diff --git a/pkgs/example.toml b/pkgs/example.toml new file mode 100644 index 00000000..659a90a9 --- /dev/null +++ b/pkgs/example.toml @@ -0,0 +1,9 @@ +dev = "rp-example" +ip = "fc00::1/64" +listen = "[::]:51821" +private_keys_dir = "/run/credentials/rp@example.service" +verbose = true + +[[peers]] +public_keys_dir = "/etc/rosenpass/example/peers/client" +allowed_ips = "fc00::2" diff --git a/pkgs/package-deb.nix b/pkgs/package-deb.nix new file mode 100644 index 00000000..c3db31ed --- /dev/null +++ b/pkgs/package-deb.nix @@ -0,0 +1,34 @@ +{ + runCommand, + dpkg, + rosenpass, +}: + +let + inherit (rosenpass) version; +in + +runCommand "rosenpass-${version}.deb" { } '' + mkdir -p packageroot/DEBIAN + + cat << EOF > packageroot/DEBIAN/control + Package: rosenpass + Version: ${version} + Architecture: all + Maintainer: Jacek Galowicz + Depends: + Description: Post-quantum-secure VPN tool Rosenpass + Rosenpass is a post-quantum-secure VPN + that uses WireGuard to transport the actual data. + EOF + + + mkdir -p packageroot/usr/bin + install -m755 -t packageroot/usr/bin ${rosenpass}/bin/* + + mkdir -p packageroot/etc/rosenpass + cp -r ${rosenpass}/lib/systemd packageroot/etc/ + cp ${./example.toml} packageroot/etc/rosenpass/example.toml + + ${dpkg}/bin/dpkg --build packageroot $out +'' diff --git a/pkgs/package-rpm.nix b/pkgs/package-rpm.nix new file mode 100644 index 00000000..b60269a2 --- /dev/null +++ b/pkgs/package-rpm.nix @@ -0,0 +1,60 @@ +{ + lib, + system, + runCommand, + rosenpass, + rpm, +}: + +let + splitVersion = lib.strings.splitString "-" rosenpass.version; + version = builtins.head splitVersion; + release = if builtins.length splitVersion != 2 then "release" else builtins.elemAt splitVersion 1; + arch = builtins.head (builtins.split "-" system); +in + +runCommand "rosenpass-${version}.rpm" { } '' + mkdir -p rpmbuild/SPECS + + cat << EOF > rpmbuild/SPECS/rosenpass.spec + Name: rosenpass + Release: ${release} + Version: ${version} + Summary: Post-quantum-secure VPN key exchange + License: Apache-2.0 + + %description + Post-quantum-secure VPN tool Rosenpass + Rosenpass is a post-quantum-secure VPN + that uses WireGuard to transport the actual data. + + %files + /usr/bin/rosenpass + /usr/bin/rp + /etc/systemd/system/rosenpass.target + /etc/systemd/system/rosenpass@.service + /etc/systemd/system/rp@.service + /etc/rosenpass/example.toml + EOF + + buildroot=rpmbuild/BUILDROOT/rosenpass-${version}-${release}.${arch} + mkdir -p $buildroot/usr/bin + install -m755 -t $buildroot/usr/bin ${rosenpass}/bin/* + + mkdir -p $buildroot/etc/rosenpass + cp -r ${rosenpass}/lib/systemd $buildroot/etc/ + chmod -R 744 $buildroot/etc/systemd + cp ${./example.toml} $buildroot/etc/rosenpass/example.toml + + export HOME=/build + mkdir -p /build/tmp + ls -R rpmbuild + + ${rpm}/bin/rpmbuild \ + -bb \ + --dbpath=$HOME \ + --define "_tmppath /build/tmp" \ + rpmbuild/SPECS/rosenpass.spec + + cp rpmbuild/RPMS/${arch}/rosenpass*.rpm $out +'' diff --git a/pkgs/release-package.nix b/pkgs/release-package.nix index 2de60298..f147c758 100644 --- a/pkgs/release-package.nix +++ b/pkgs/release-package.nix @@ -1,21 +1,24 @@ -{ lib, stdenvNoCC, runCommandNoCC, pkgsStatic, rosenpass, rosenpass-oci-image, rp } @ args: +{ + lib, + stdenvNoCC, + runCommandNoCC, + pkgsStatic, + rosenpass, + rosenpass-oci-image, + rp, +}@args: let version = rosenpass.version; # select static packages on Linux, default packages otherwise - package = - if stdenvNoCC.hostPlatform.isLinux then - pkgsStatic.rosenpass - else args.rosenpass; - rp = - if stdenvNoCC.hostPlatform.isLinux then - pkgsStatic.rp - else args.rp; + package = if stdenvNoCC.hostPlatform.isLinux then pkgsStatic.rosenpass else args.rosenpass; + rp = if stdenvNoCC.hostPlatform.isLinux then pkgsStatic.rp else args.rp; oci-image = if stdenvNoCC.hostPlatform.isLinux then pkgsStatic.rosenpass-oci-image - else args.rosenpass-oci-image; + else + args.rosenpass-oci-image; in runCommandNoCC "lace-result" { } '' mkdir {bin,$out} diff --git a/pkgs/rosenpass-oci-image.nix b/pkgs/rosenpass-oci-image.nix index f68e0377..3008e7a6 100644 --- a/pkgs/rosenpass-oci-image.nix +++ b/pkgs/rosenpass-oci-image.nix @@ -1,4 +1,8 @@ -{ dockerTools, buildEnv, rosenpass }: +{ + dockerTools, + buildEnv, + rosenpass, +}: dockerTools.buildImage { name = rosenpass.name + "-oci"; diff --git a/pkgs/rosenpass.nix b/pkgs/rosenpass.nix index ff4e0ec3..c25809f1 100644 --- a/pkgs/rosenpass.nix +++ b/pkgs/rosenpass.nix @@ -1,4 +1,13 @@ -{ lib, stdenv, rustPlatform, cmake, mandoc, removeReferencesTo, bash, package ? "rosenpass" }: +{ + lib, + stdenv, + rustPlatform, + cmake, + mandoc, + removeReferencesTo, + bash, + package ? "rosenpass", +}: let # whether we want to build a statically linked binary @@ -17,24 +26,30 @@ let "toml" ]; # Files to explicitly include - files = [ - "to/README.md" - ]; + files = [ "to/README.md" ]; src = ../.; - filter = (path: type: scoped rec { - inherit (lib) any id removePrefix hasSuffix; - anyof = (any id); + filter = ( + path: type: + scoped rec { + inherit (lib) + any + id + removePrefix + hasSuffix + ; + anyof = (any id); - basename = baseNameOf (toString path); - relative = removePrefix (toString src + "/") (toString path); + basename = baseNameOf (toString path); + relative = removePrefix (toString src + "/") (toString path); - result = anyof [ - (type == "directory") - (any (ext: hasSuffix ".${ext}" basename) extensions) - (any (file: file == relative) files) - ]; - }); + result = anyof [ + (type == "directory") + (any (ext: hasSuffix ".${ext}" basename) extensions) + (any (file: file == relative) files) + ]; + } + ); result = lib.sources.cleanSourceWith { inherit src filter; }; }; @@ -47,8 +62,14 @@ rustPlatform.buildRustPackage { version = cargoToml.package.version; inherit src; - cargoBuildOptions = [ "--package" package ]; - cargoTestOptions = [ "--package" package ]; + cargoBuildOptions = [ + "--package" + package + ]; + cargoTestOptions = [ + "--package" + package + ]; doCheck = true; @@ -57,6 +78,8 @@ rustPlatform.buildRustPackage { outputHashes = { "memsec-0.6.3" = "sha256-4ri+IEqLd77cLcul3lZrmpDKj4cwuYJ8oPRAiQNGeLw="; "uds-0.4.2" = "sha256-qlxr/iJt2AV4WryePIvqm/8/MK/iqtzegztNliR93W8="; + "libcrux-blake2-0.0.3-pre" = "sha256-0CLjuzwJqGooiODOHf5D8Hc8ClcG/XcGvVGyOVnLmJY="; + "libcrux-macros-0.0.3" = "sha256-Tb5uRirwhRhoFEK8uu1LvXl89h++40pxzZ+7kXe8RAI="; }; }; @@ -80,7 +103,10 @@ rustPlatform.buildRustPackage { meta = { inherit (cargoToml.package) description homepage; - license = with lib.licenses; [ mit asl20 ]; + license = with lib.licenses; [ + mit + asl20 + ]; maintainers = [ lib.maintainers.wucke13 ]; platforms = lib.platforms.all; }; diff --git a/pkgs/whitepaper.nix b/pkgs/whitepaper.nix index 558e9673..52312a20 100644 --- a/pkgs/whitepaper.nix +++ b/pkgs/whitepaper.nix @@ -1,13 +1,53 @@ -{ stdenvNoCC, texlive, ncurses, python3Packages, which }: +{ + stdenvNoCC, + texlive, + ncurses, + python3Packages, + which, +}: let - customTexLiveSetup = (texlive.combine { - inherit (texlive) acmart amsfonts biber biblatex biblatex-software - biblatex-trad ccicons csquotes csvsimple doclicense eso-pic fancyvrb - fontspec gitinfo2 gobble ifmtarg koma-script latexmk lm lualatex-math - markdown mathtools minted noto nunito paralist pgf scheme-basic soul - unicode-math upquote xifthen xkeyval xurl; - }); + customTexLiveSetup = ( + texlive.combine { + inherit (texlive) + acmart + amsfonts + biber + biblatex + biblatex-software + biblatex-trad + ccicons + csquotes + csvsimple + doclicense + eso-pic + fancyvrb + fontspec + gitinfo2 + gobble + ifmtarg + koma-script + latexmk + lm + lualatex-math + markdown + mathtools + minted + noto + nunito + paralist + pgf + scheme-basic + soul + unicode-math + upquote + xifthen + xkeyval + xurl + dirtytalk + ; + } + ); in stdenvNoCC.mkDerivation { name = "whitepaper"; diff --git a/readme.md b/readme.md index 8975ce5e..6021361c 100644 --- a/readme.md +++ b/readme.md @@ -14,7 +14,7 @@ This repository contains ## Getting started -First, [install rosenpass](#Getting-Rosenpass). Then, check out the help functions of `rp` & `rosenpass`: +First, [install rosenpass](#getting-rosenpass). Then, check out the help functions of `rp` & `rosenpass`: ```sh rp help @@ -64,11 +64,7 @@ The analysis is implemented according to modern software engineering principles: The code uses a variety of optimizations to speed up analysis such as using secret functions to model trusted/malicious setup. We split the model into two separate entry points which can be analyzed in parallel. Each is much faster than both models combined. A wrapper script provides instant feedback about which queries execute as expected in color: A red cross if a query fails and a green check if it succeeds. -[^liboqs]: https://openquantumsafe.org/liboqs/ -[^wg]: https://www.wireguard.com/ -[^pqwg]: https://eprint.iacr.org/2020/379 -[^pqwg-statedis]: Unless supplied with a pre-shared-key, but this defeats the purpose of a key exchange protocol -[^wg-statedis]: https://lists.zx2c4.com/pipermail/wireguard/2021-August/006916.htmlA +[^liboqs]: # Getting Rosenpass @@ -78,6 +74,56 @@ Rosenpass is packaged for more and more distributions, maybe also for the distri [![Packaging status](https://repology.org/badge/vertical-allrepos/rosenpass.svg)](https://repology.org/project/rosenpass/versions) +## Docker Images + +Rosenpass is also available as prebuilt Docker images: + +- [`ghcr.io/rosenpass/rosenpass`](https://github.com/rosenpass/rosenpass/pkgs/container/rosenpass) +- [`ghcr.io/rosenpass/rp`](https://github.com/rosenpass/rosenpass/pkgs/container/rp) + +For details on how to use these images, refer to the [Docker usage guide](docker/USAGE.md). + +## Benchmarks + +This repository contains facilities for benchmarking both the Rosenpass +protocol code and the implementations of the cryptographic primitives used +by it. The primitives are benchmarked using criterion. For the protocol code +benchmarks we use a library for instrumenting the code such that events are +written to a trace, which is then inspected after a run. + +Benchmarks are automatically run on CI. The measurements are visualized in the +[Benchmark Dashboard]. + +[Benchmark Dashboard]: https://rosenpass.github.io/rosenpass/benchmarks + +### Primitive Benchmarks + +There are benchmarks for the functions of the traits `Kem`, `Aead` and +`KeyedHash`. They are run for all implementations in the `primitives` +benchmark of `rosenpass-ciphers`. Run the benchmarks and view their results using + +``` +cargo bench -p rosenpass-ciphers --bench primitives -F bench +``` + +Note that the `bench` feature enables the inclusion of the libcrux-backed +trait implementations in the module tree, but does not enable them +as default. + +### Protocol Benchmarks + +The trace that is being written to lives in a new module +`trace_bench` in the util crate. A basic benchmark that +performs some minor statistical analysis of the trace can be run using + +``` +cargo bench -p rosenpass --bench trace_handshake -F trace_bench +``` + +This runs the benchmarks and prints the results in machine-readable JSON. + +--- + # Mirrors Don't want to use GitHub or only have an IPv6 connection? Rosenpass has set up two mirrors for this: diff --git a/rosenpass/Cargo.toml b/rosenpass/Cargo.toml index be0bf77f..c23d1f38 100644 --- a/rosenpass/Cargo.toml +++ b/rosenpass/Cargo.toml @@ -8,6 +8,7 @@ description = "Build post-quantum-secure VPNs with WireGuard!" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [[bin]] name = "rosenpass" @@ -28,7 +29,16 @@ required-features = ["experiment_api", "internal_testing"] [[test]] name = "gen-ipc-msg-types" -required-features = ["experiment_api", "internal_testing", "internal_bin_gen_ipc_msg_types"] +required-features = [ + "experiment_api", + "internal_testing", + "internal_bin_gen_ipc_msg_types", +] + +[[bench]] +name = "trace_handshake" +harness = false +required-features = ["trace_bench"] [[bench]] name = "handshake" @@ -67,6 +77,7 @@ command-fds = { workspace = true, optional = true } rustix = { workspace = true, optional = true } uds = { workspace = true, optional = true, features = ["mio_1xx"] } signal-hook = { workspace = true, optional = true } +libcrux-test-utils = { workspace = true, optional = true } [build-dependencies] anyhow = { workspace = true } @@ -81,20 +92,27 @@ tempfile = { workspace = true } rustix = { workspace = true } [features] -default = [] +#default = ["experiment_libcrux_all"] +experiment_cookie_dos_mitigation = [] experiment_memfd_secret = ["rosenpass-wireguard-broker/experiment_memfd_secret"] -experiment_libcrux = ["rosenpass-ciphers/experiment_libcrux"] +experiment_libcrux_all = ["rosenpass-ciphers/experiment_libcrux_all"] +experiment_libcrux_blake2 = ["rosenpass-ciphers/experiment_libcrux_blake2"] +experiment_libcrux_chachapoly = [ + "rosenpass-ciphers/experiment_libcrux_chachapoly", +] +experiment_libcrux_kyber = ["rosenpass-ciphers/experiment_libcrux_kyber"] experiment_api = [ - "hex-literal", - "uds", - "command-fds", - "rustix", - "rosenpass-util/experiment_file_descriptor_passing", - "rosenpass-wireguard-broker/experiment_api", + "hex-literal", + "uds", + "command-fds", + "rustix", + "rosenpass-util/experiment_file_descriptor_passing", + "rosenpass-wireguard-broker/experiment_api", ] internal_signal_handling_for_coverage_reports = ["signal-hook"] internal_testing = [] internal_bin_gen_ipc_msg_types = ["hex", "heck"] +trace_bench = ["rosenpass-util/trace_bench", "dep:libcrux-test-utils"] [lints.rust] unexpected_cfgs = { level = "allow", check-cfg = ['cfg(coverage)'] } diff --git a/rosenpass/benches/handshake.rs b/rosenpass/benches/handshake.rs index bcb98992..cceafcba 100644 --- a/rosenpass/benches/handshake.rs +++ b/rosenpass/benches/handshake.rs @@ -1,13 +1,16 @@ -use anyhow::Result; -use rosenpass::protocol::{CryptoServer, HandleMsgResult, MsgBuf, PeerPtr, SPk, SSk, SymKey}; use std::ops::DerefMut; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; - +use anyhow::Result; use criterion::{black_box, criterion_group, criterion_main, Criterion}; + +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; use rosenpass_secret_memory::secret_policy_try_use_memfd_secrets; +use rosenpass::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey}; +use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; +use rosenpass::protocol::{CryptoServer, HandleMsgResult, PeerPtr, ProtocolVersion}; + fn handle( tx: &mut CryptoServer, msgb: &mut MsgBuf, @@ -41,25 +44,43 @@ fn hs(ini: &mut CryptoServer, res: &mut CryptoServer) -> Result<()> { fn keygen() -> Result<(SSk, SPk)> { let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(sk.secret_mut(), pk.deref_mut())?; + StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?; Ok((sk, pk)) } -fn make_server_pair() -> Result<(CryptoServer, CryptoServer)> { +fn make_server_pair(protocol_version: ProtocolVersion) -> Result<(CryptoServer, CryptoServer)> { let psk = SymKey::random(); let ((ska, pka), (skb, pkb)) = (keygen()?, keygen()?); let (mut a, mut b) = ( CryptoServer::new(ska, pka.clone()), CryptoServer::new(skb, pkb.clone()), ); - a.add_peer(Some(psk.clone()), pkb)?; - b.add_peer(Some(psk), pka)?; + a.add_peer( + Some(psk.clone()), + pkb, + protocol_version.clone(), + OskDomainSeparator::default(), + )?; + b.add_peer( + Some(psk), + pka, + protocol_version, + OskDomainSeparator::default(), + )?; Ok((a, b)) } -fn criterion_benchmark(c: &mut Criterion) { +fn criterion_benchmark_v02(c: &mut Criterion) { + criterion_benchmark(c, ProtocolVersion::V02) +} + +fn criterion_benchmark_v03(c: &mut Criterion) { + criterion_benchmark(c, ProtocolVersion::V03) +} + +fn criterion_benchmark(c: &mut Criterion, protocol_version: ProtocolVersion) { secret_policy_try_use_memfd_secrets(); - let (mut a, mut b) = make_server_pair().unwrap(); + let (mut a, mut b) = make_server_pair(protocol_version).unwrap(); c.bench_function("cca_secret_alloc", |bench| { bench.iter(|| { SSk::zero(); @@ -82,5 +103,6 @@ fn criterion_benchmark(c: &mut Criterion) { }); } -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); +criterion_group!(benches_v02, criterion_benchmark_v02); +criterion_group!(benches_v03, criterion_benchmark_v03); +criterion_main!(benches_v02, benches_v03); diff --git a/rosenpass/benches/trace_handshake.rs b/rosenpass/benches/trace_handshake.rs new file mode 100644 index 00000000..8f55ed57 --- /dev/null +++ b/rosenpass/benches/trace_handshake.rs @@ -0,0 +1,393 @@ +use std::io::{self, Write}; +use std::time::{Duration, Instant}; +use std::{collections::HashMap, hint::black_box, ops::DerefMut}; + +use anyhow::Result; + +use libcrux_test_utils::tracing::{EventType, Trace as _}; + +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; +use rosenpass_secret_memory::secret_policy_try_use_memfd_secrets; +use rosenpass_util::trace_bench::RpEventType; + +use rosenpass::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey}; +use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; +use rosenpass::protocol::{CryptoServer, HandleMsgResult, PeerPtr, ProtocolVersion}; + +const ITERATIONS: usize = 100; + +/// Performs a full protocol run by processing a message and recursing into handling that message, +/// until no further response is produced. Returns the keys produce by the two parties. +/// +/// Ensures that each party produces one of the two keys. +fn handle( + tx: &mut CryptoServer, + msgb: &mut MsgBuf, + msgl: usize, + rx: &mut CryptoServer, + resb: &mut MsgBuf, +) -> Result<(Option, Option)> { + let HandleMsgResult { + exchanged_with: xch, + resp, + } = rx.handle_msg(&msgb[..msgl], &mut **resb)?; + + assert!(matches!(xch, None | Some(PeerPtr(0)))); + + let xch = xch.map(|p| rx.osk(p).unwrap()); + + let (rxk, txk) = resp + .map(|resl| handle(rx, resb, resl, tx, msgb)) + .transpose()? + .unwrap_or((None, None)); + + assert!(rxk.is_none() || xch.is_none()); + + Ok((txk, rxk.or(xch))) +} + +/// Performs the full handshake by calling `handle` with the correct values, based on just two +/// `CryptoServer`s. +/// +/// Ensures that both parties compute the same keys. +fn hs(ini: &mut CryptoServer, res: &mut CryptoServer) -> Result<()> { + let (mut inib, mut resb) = (MsgBuf::zero(), MsgBuf::zero()); + let sz = ini.initiate_handshake(PeerPtr(0), &mut *inib)?; + let (kini, kres) = handle(ini, &mut inib, sz, res, &mut resb)?; + assert!(kini.unwrap().secret() == kres.unwrap().secret()); + Ok(()) +} + +/// Generates a new key pair. +fn keygen() -> Result<(SSk, SPk)> { + let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); + StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?; + Ok((sk, pk)) +} + +/// Creates two instanves of `CryptoServer`, generating key pairs for each. +fn make_server_pair(protocol_version: ProtocolVersion) -> Result<(CryptoServer, CryptoServer)> { + let psk = SymKey::random(); + let ((ska, pka), (skb, pkb)) = (keygen()?, keygen()?); + let (mut a, mut b) = ( + CryptoServer::new(ska, pka.clone()), + CryptoServer::new(skb, pkb.clone()), + ); + a.add_peer( + Some(psk.clone()), + pkb, + protocol_version.clone(), + OskDomainSeparator::default(), + )?; + b.add_peer( + Some(psk), + pka, + protocol_version, + OskDomainSeparator::default(), + )?; + Ok((a, b)) +} + +fn main() { + let trace = rosenpass_util::trace_bench::trace(); + + // Attempt to use memfd_secrets for storing sensitive key material + secret_policy_try_use_memfd_secrets(); + + // Run protocol for V02 + let (mut a_v02, mut b_v02) = make_server_pair(ProtocolVersion::V02).unwrap(); + for _ in 0..ITERATIONS { + hs(black_box(&mut a_v02), black_box(&mut b_v02)).unwrap(); + } + + // Emit a marker event to separate V02 and V03 trace sections + trace.emit_on_the_fly("start-hs-v03"); + + // Run protocol for V03 + let (mut a_v03, mut b_v03) = make_server_pair(ProtocolVersion::V03).unwrap(); + for _ in 0..ITERATIONS { + hs(black_box(&mut a_v03), black_box(&mut b_v03)).unwrap(); + } + + // Collect the trace events generated during the handshakes + let trace: Vec<_> = trace.clone().report(); + + // Split the trace into V02 and V03 sections based on the marker + let (trace_v02, trace_v03) = { + let cutoff = trace + .iter() + .position(|entry| entry.label == "start-hs-v03") + .unwrap(); + // Exclude the marker itself from the V03 trace + let (v02, v03_with_marker) = trace.split_at(cutoff); + (v02, &v03_with_marker[1..]) + }; + + // Perform statistical analysis on both trace sections and write results as JSON + write_json_arrays( + &mut std::io::stdout(), // Write to standard output + vec![ + ("V02", statistical_analysis(trace_v02.to_vec())), + ("V03", statistical_analysis(trace_v03.to_vec())), + ], + ) + .expect("error writing json data"); +} + +/// Performs a simple statistical analysis: +/// - bins trace events by label +/// - extracts durations of spamns +/// - filters out empty bins +/// - calculates aggregate statistics (mean, std dev) +fn statistical_analysis(trace: Vec) -> Vec<(&'static str, AggregateStat)> { + bin_events(trace) + .into_iter() + .map(|(label, spans)| (label, extract_span_durations(label, spans.as_slice()))) + .filter(|(_, durations)| !durations.is_empty()) + .map(|(label, durations)| (label, AggregateStat::analyze_durations(&durations))) + .collect() +} + +/// Takes an iterator of ("protocol_version", iterator_of_stats) pairs and writes them +/// as a single flat JSON array to the provided writer. +/// +/// # Arguments +/// * `w` - The writer to output JSON to (e.g., stdout, file). +/// * `item_groups` - An iterator producing tuples `(version, stats): (&'static str, II)`. +/// Here `II` is itself an iterator producing `(label, agg_stat): (&'static str, AggregateStat)`, +/// where the label is the label of the span, e.g. "IHI2". +/// +/// # Type Parameters +/// * `W` - A type that implements `std::io::Write`. +/// * `II` - An iterator type yielding (`&'static str`, `AggregateStat`). +fn write_json_arrays)>>( + w: &mut W, + item_groups: impl IntoIterator, +) -> io::Result<()> { + // Flatten the groups into a single iterator of (protocol_version, label, stats) + let iter = item_groups.into_iter().flat_map(|(version, items)| { + items + .into_iter() + .map(move |(label, agg_stat)| (version, label, agg_stat)) + }); + let mut delim = ""; // Start with no delimiter + + // Start the JSON array + write!(w, "[")?; + + // Write the flattened statistics as JSON objects, separated by commas. + for (version, label, agg_stat) in iter { + write!(w, "{delim}")?; // Write delimiter (empty for first item, "," for subsequent) + agg_stat.write_json_ns(label, version, w)?; // Write the JSON object for the stat entry + delim = ","; // Set delimiter for the next iteration + } + + // End the JSON array + write!(w, "]") +} + +/// Used to group benchmark results in visualizations +enum RunTimeGroup { + /// For particularly long operations. + Long, + /// Operations of moderate duration. + Medium, + /// Operations expected to complete under a millisecond. + BelowMillisec, + /// Very fast operations, likely under a microsecond. + BelowMicrosec, +} + +impl std::fmt::Display for RunTimeGroup { + /// Used when writing the group information to JSON output. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let txt = match self { + RunTimeGroup::Long => "long", + RunTimeGroup::Medium => "medium", + RunTimeGroup::BelowMillisec => "below 1ms", + RunTimeGroup::BelowMicrosec => "below 1us", + }; + write!(f, "{txt}") + } +} + +/// Maps specific internal timing labels (likely from rosenpass internals) +/// to the broader SpanGroup categories. +fn run_time_group(label: &str) -> RunTimeGroup { + match label { + // Explicitly categorized labels based on expected performance characteristics + "handle_init_hello" | "handle_resp_hello" | "RHI5" | "IHR5" => RunTimeGroup::Long, + "RHR1" | "IHI2" | "ICR6" => RunTimeGroup::BelowMicrosec, + "RHI6" | "ICI7" | "ICR7" | "RHR3" | "ICR3" | "IHR8" | "ICI4" | "RHI3" | "RHI4" | "RHR4" + | "RHR7" | "ICI3" | "IHI3" | "IHI8" | "ICR2" | "ICR4" | "IHR4" | "IHR6" | "IHI4" + | "RHI7" => RunTimeGroup::BelowMillisec, + // Default protocol_version for any other labels + _ => RunTimeGroup::Medium, + } +} + +/// Used temporarily within `extract_span_durations` to track open spans +/// and calculated durations. +#[derive(Debug, Clone)] +enum StatEntry { + /// Represents an unmatched SpanOpen event with its timestamp. + Start(Instant), + /// Represents a completed span with its calculated duration. + Duration(Duration), +} + +/// Takes a flat list of events and organizes them into a HashMap where keys +/// are event labels and values are vectors of events with that label. +fn bin_events(events: Vec) -> HashMap<&'static str, Vec> { + let mut spans = HashMap::<_, Vec<_>>::new(); + for event in events { + // Get the vector for the event's label, or create a new one + let spans_for_label = spans.entry(event.label).or_default(); + // Add the event to the vector + spans_for_label.push(event); + } + spans +} + +/// Processes a list of events (assumed to be for the same label), matching +/// `SpanOpen` and `SpanClose` events to calculate the duration of each span. +/// It handles potentially interleaved spans correctly. +fn extract_span_durations(label: &str, events: &[RpEventType]) -> Vec { + let mut processing_list: Vec = vec![]; // List to track open spans and final durations + + for entry in events { + match &entry.ty { + EventType::SpanOpen => { + // Record the start time of a new span + processing_list.push(StatEntry::Start(entry.at)); + } + EventType::SpanClose => { + // Find the most recent unmatched 'Start' entry + let start_index = processing_list + .iter() + .rposition(|span| matches!(span, StatEntry::Start(_))); // Find last Start + + match start_index { + Some(index) => { + // Retrieve the start time + let start_time = match processing_list[index] { + StatEntry::Start(t) => t, + _ => unreachable!(), // Should always be Start based on rposition logic + }; + // Calculate duration and replace the 'Start' entry with 'Duration' + processing_list[index] = StatEntry::Duration(entry.at - start_time); + } + None => { + // This should not happen with well-formed traces + eprintln!( + "Warning: Found SpanClose without a matching SpanOpen for label '{}': {:?}", + label, entry + ); + } + } + } + EventType::OnTheFly => { + // Ignore OnTheFly events for duration calculation + } + } + } + + // Collect all calculated durations, reporting any unmatched starts + processing_list + .into_iter() + .filter_map(|span| match span { + StatEntry::Start(at) => { + // Report error if a span was opened but never closed + eprintln!( + "Warning: Unmatched SpanOpen at {:?} for label '{}'", + at, label + ); + None // Discard unmatched starts + } + StatEntry::Duration(dur) => Some(dur), // Keep calculated durations + }) + .collect() +} + +/// Stores the mean, standard deviation, relative standard deviation (sd/mean), +/// and the number of samples used for calculation. +#[derive(Debug)] +struct AggregateStat { + /// Average duration. + mean_duration: T, + /// Standard deviation of durations. + sd_duration: T, + /// Standard deviation as a percentage of the mean. + sd_by_mean: String, + /// Number of duration measurements. + sample_size: usize, +} + +impl AggregateStat { + /// Calculates mean, variance, and standard deviation for a slice of Durations. + fn analyze_durations(durations: &[Duration]) -> Self { + let sample_size = durations.len(); + assert!(sample_size > 0, "Cannot analyze empty duration slice"); + + // Calculate the sum of durations + let sum: Duration = durations.iter().sum(); + // Calculate the mean duration + let mean = sum / (sample_size as u32); + + // Calculate mean in nanoseconds, adding 1 to avoid potential division by zero later + // (though highly unlikely with realistic durations) + let mean_ns = mean.as_nanos().saturating_add(1); + + // Calculate variance (sum of squared differences from the mean) / N + let variance = durations + .iter() + .map(Duration::as_nanos) + .map(|d_ns| d_ns.abs_diff(mean_ns).pow(2)) // (duration_ns - mean_ns)^2 + .sum::() // Sum of squares + / (sample_size as u128); // Divide by sample size + + // Calculate standard deviation (sqrt of variance) + let sd_ns = (variance as f64).sqrt() as u128; + let sd = Duration::from_nanos(sd_ns as u64); // Convert back to Duration + + // Calculate relative standard deviation (sd / mean) as a percentage string + let sd_rel_permille = (10000 * sd_ns).checked_div(mean_ns).unwrap_or(0); // Calculate sd/mean * 10000 + let sd_rel_formatted = format!("{}.{:02}%", sd_rel_permille / 100, sd_rel_permille % 100); + + AggregateStat { + mean_duration: mean, + sd_duration: sd, + sd_by_mean: sd_rel_formatted, + sample_size, + } + } + + /// Writes the statistics as a JSON object to the provided writer. + /// Includes metadata like label, protocol_version, OS, architecture, and run time group. + /// + /// # Arguments + /// * `label` - The specific benchmark/span label. + /// * `protocol_version` - Version of the protocol that is benchmarked. + /// * `w` - The output writer (must implement `std::io::Write`). + fn write_json_ns( + &self, + label: &str, + protocol_version: &str, + w: &mut impl io::Write, + ) -> io::Result<()> { + // Format the JSON string using measured values and environment constants + writeln!( + w, + r#"{{"name":"{name}", "unit":"ns/iter", "value":"{value}", "range":"± {range}", "protocol version":"{protocol_version}", "sample size":"{sample_size}", "operating system":"{os}", "architecture":"{arch}", "run time":"{run_time}"}}"#, + name = label, // Benchmark name + value = self.mean_duration.as_nanos(), // Mean duration in nanoseconds + range = self.sd_duration.as_nanos(), // Standard deviation in nanoseconds + sample_size = self.sample_size, // Number of samples + os = std::env::consts::OS, // Operating system + arch = std::env::consts::ARCH, // CPU architecture + run_time = run_time_group(label), // Run time group category (long, medium, etc.) + protocol_version = protocol_version // Overall protocol_version (e.g., protocol version) + ) + } +} diff --git a/rosenpass/src/api/api_handler.rs b/rosenpass/src/api/api_handler.rs index c86d57c4..dcd85cca 100644 --- a/rosenpass/src/api/api_handler.rs +++ b/rosenpass/src/api/api_handler.rs @@ -158,10 +158,10 @@ where ); // Actually read the secrets - let mut sk = crate::protocol::SSk::zero(); + let mut sk = crate::protocol::basic_types::SSk::zero(); sk_io.read_exact_til_end(sk.secret_mut()).einvalid_req()?; - let mut pk = crate::protocol::SPk::zero(); + let mut pk = crate::protocol::basic_types::SPk::zero(); pk_io.read_exact_til_end(pk.borrow_mut()).einvalid_req()?; // Retrieve the construction site diff --git a/rosenpass/src/api/config.rs b/rosenpass/src/api/config.rs index 122bfdbe..0fa11b8b 100644 --- a/rosenpass/src/api/config.rs +++ b/rosenpass/src/api/config.rs @@ -8,6 +8,7 @@ use crate::app_server::AppServer; /// Configuration options for the Rosenpass API #[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq)] +#[serde(deny_unknown_fields)] pub struct ApiConfig { /// Where in the file-system to create the unix socket the rosenpass API will be listening for /// connections on diff --git a/rosenpass/src/app_server.rs b/rosenpass/src/app_server.rs index 75798b87..cd406f92 100644 --- a/rosenpass/src/app_server.rs +++ b/rosenpass/src/app_server.rs @@ -1,55 +1,34 @@ -/// This contains the bulk of the rosenpass server IO handling code whereas -/// the actual cryptographic code lives in the [crate::protocol] module -use anyhow::bail; +//! This contains the bulk of the rosenpass server IO handling code whereas +//! the actual cryptographic code lives in the [crate::protocol] module -use anyhow::Context; -use anyhow::Result; +use std::collections::{HashMap, VecDeque}; +use std::io::{stdout, ErrorKind, Write}; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; +use std::time::{Duration, Instant}; +use std::{cell::Cell, fmt::Debug, io, path::PathBuf, slice}; + +use anyhow::{bail, Context, Result}; use derive_builder::Builder; use log::{error, info, warn}; -use mio::Interest; -use mio::Token; -use rosenpass_secret_memory::Public; -use rosenpass_secret_memory::Secret; -use rosenpass_util::build::ConstructionSite; -use rosenpass_util::file::StoreValueB64; -use rosenpass_util::functional::run; -use rosenpass_util::functional::ApplyExt; -use rosenpass_util::io::IoResultKindHintExt; -use rosenpass_util::io::SubstituteForIoErrorKindExt; -use rosenpass_util::option::SomeExt; -use rosenpass_util::result::OkExt; -use rosenpass_wireguard_broker::WireguardBrokerMio; -use rosenpass_wireguard_broker::{WireguardBrokerCfg, WG_KEY_LEN}; +use mio::{Interest, Token}; use zerocopy::AsBytes; -use std::cell::Cell; - -use std::collections::HashMap; -use std::collections::VecDeque; -use std::fmt::Debug; -use std::io; -use std::io::stdout; -use std::io::ErrorKind; -use std::io::Write; -use std::net::Ipv4Addr; -use std::net::Ipv6Addr; -use std::net::SocketAddr; -use std::net::SocketAddrV4; -use std::net::SocketAddrV6; -use std::net::ToSocketAddrs; -use std::path::PathBuf; -use std::slice; -use std::time::Duration; -use std::time::Instant; - -use crate::protocol::BuildCryptoServer; -use crate::protocol::HostIdentification; -use crate::{ - config::Verbosity, - protocol::{CryptoServer, MsgBuf, PeerPtr, SPk, SSk, SymKey, Timing}, -}; use rosenpass_util::attempt; -use rosenpass_util::b64::B64Display; +use rosenpass_util::functional::{run, ApplyExt}; +use rosenpass_util::io::{IoResultKindHintExt, SubstituteForIoErrorKindExt}; +use rosenpass_util::{ + b64::B64Display, build::ConstructionSite, file::StoreValueB64, option::SomeExt, result::OkExt, +}; + +use rosenpass_secret_memory::{Public, Secret}; +use rosenpass_wireguard_broker::{WireguardBrokerCfg, WireguardBrokerMio, WG_KEY_LEN}; + +use crate::config::{ProtocolVersion, Verbosity}; + +use crate::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey}; +use crate::protocol::osk_domain_separator::OskDomainSeparator; +use crate::protocol::timing::Timing; +use crate::protocol::{BuildCryptoServer, CryptoServer, HostIdentification, PeerPtr}; /// The maximum size of a base64 encoded symmetric key (estimate) pub const MAX_B64_KEY_SIZE: usize = 32 * 5 / 3; @@ -332,7 +311,7 @@ pub struct AppServer { /// /// Because the API supports initializing the server with a keypair /// and CryptoServer needs to be initialized with a keypair, the struct - /// struct is wrapped in a ConstructionSite + /// is wrapped in a ConstructionSite pub crypto_site: ConstructionSite, /// The UDP sockets used to send and receive protocol messages pub sockets: Vec, @@ -1035,6 +1014,7 @@ impl AppServer { /// # Examples /// /// See [Self::new]. + #[allow(clippy::too_many_arguments)] pub fn add_peer( &mut self, psk: Option, @@ -1042,11 +1022,17 @@ impl AppServer { outfile: Option, broker_peer: Option, hostname: Option, + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, ) -> anyhow::Result { let PeerPtr(pn) = match &mut self.crypto_site { ConstructionSite::Void => bail!("Crypto server construction site is void"), - ConstructionSite::Builder(builder) => builder.add_peer(psk, pk), - ConstructionSite::Product(srv) => srv.add_peer(psk, pk)?, + ConstructionSite::Builder(builder) => { + builder.add_peer(psk, pk, protocol_version, osk_domain_separator) + } + ConstructionSite::Product(srv) => { + srv.add_peer(psk, pk, protocol_version.into(), osk_domain_separator)? + } }; assert!(pn == self.peers.len()); @@ -1262,7 +1248,7 @@ impl AppServer { } /// Used as a helper by [Self::event_loop_without_error_handling] when - /// a new output key has been echanged + /// a new output key has been exchanged pub fn output_key( &mut self, peer: AppPeerPtr, @@ -1335,7 +1321,7 @@ impl AppServer { break A::SendRetransmission(AppPeerPtr(no)) } Some(C::Sleep(timeout)) => timeout, // No event from crypto-server, do IO - None => crate::protocol::UNENDING, // Crypto server is uninitialized, do IO + None => crate::protocol::timing::UNENDING, // Crypto server is uninitialized, do IO }; // Perform IO (look for a message) diff --git a/rosenpass/src/bin/gen-ipc-msg-types.rs b/rosenpass/src/bin/gen-ipc-msg-types.rs index 028113ba..64eb27bd 100644 --- a/rosenpass/src/bin/gen-ipc-msg-types.rs +++ b/rosenpass/src/bin/gen-ipc-msg-types.rs @@ -1,6 +1,7 @@ use anyhow::{Context, Result}; use heck::ToShoutySnakeCase; +use rosenpass_ciphers::subtle::keyed_hash::KeyedHash; use rosenpass_ciphers::{hash_domain::HashDomain, KEY_LEN}; /// Recursively calculate a concrete hash value for an API message type @@ -12,12 +13,12 @@ fn calculate_hash_value(hd: HashDomain, values: &[&str]) -> Result<[u8; KEY_LEN] } /// Print a hash literal for pasting into the Rosenpass source code -fn print_literal(path: &[&str]) -> Result<()> { - let val = calculate_hash_value(HashDomain::zero(), path)?; +fn print_literal(path: &[&str], shake_or_blake: KeyedHash) -> Result<()> { + let val = calculate_hash_value(HashDomain::zero(shake_or_blake.clone()), path)?; let (last, prefix) = path.split_last().context("developer error!")?; let var_name = last.to_shouty_snake_case(); - print!("// hash domain hash of: "); + print!("// hash domain hash with hash {} of: ", shake_or_blake); for n in prefix.iter() { print!("{n} -> "); } @@ -51,24 +52,24 @@ impl Tree { } } - fn gen_code_inner(&self, prefix: &[&str]) -> Result<()> { + fn gen_code_inner(&self, prefix: &[&str], shake_or_blake: KeyedHash) -> Result<()> { let mut path = prefix.to_owned(); path.push(self.name()); match self { Self::Branch(_, ref children) => { for c in children.iter() { - c.gen_code_inner(&path)? + c.gen_code_inner(&path, shake_or_blake.clone())? } } - Self::Leaf(_) => print_literal(&path)?, + Self::Leaf(_) => print_literal(&path, shake_or_blake)?, }; Ok(()) } - fn gen_code(&self) -> Result<()> { - self.gen_code_inner(&[]) + fn gen_code(&self, shake_or_blake: KeyedHash) -> Result<()> { + self.gen_code_inner(&[], shake_or_blake) } } @@ -93,5 +94,7 @@ fn main() -> Result<()> { println!("type RawMsgType = u128;"); println!(); - tree.gen_code() + tree.gen_code(KeyedHash::keyed_shake256())?; + println!(); + tree.gen_code(KeyedHash::incorrect_hmac_blake2b()) } diff --git a/rosenpass/src/cli.rs b/rosenpass/src/cli.rs index 870045f1..186f617a 100644 --- a/rosenpass/src/cli.rs +++ b/rosenpass/src/cli.rs @@ -5,8 +5,8 @@ use anyhow::{bail, ensure, Context}; use clap::{Parser, Subcommand}; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; use rosenpass_secret_memory::file::StoreSecret; use rosenpass_util::file::{LoadValue, LoadValueB64, StoreValue}; use rosenpass_wireguard_broker::brokers::native_unix::{ @@ -17,7 +17,7 @@ use std::path::PathBuf; use crate::app_server::AppServerTest; use crate::app_server::{AppServer, BrokerPeer}; -use crate::protocol::{SPk, SSk, SymKey}; +use crate::protocol::basic_types::{SPk, SSk, SymKey}; use super::config; @@ -490,6 +490,8 @@ impl CliArgs { cfg_peer.key_out, broker_peer, cfg_peer.endpoint.clone(), + cfg_peer.protocol_version.into(), + cfg_peer.osk_domain_separator.try_into()?, )?; } @@ -606,9 +608,9 @@ impl CliArgs { /// generate secret and public keys, store in files according to the paths passed as arguments pub fn generate_and_save_keypair(secret_key: PathBuf, public_key: PathBuf) -> anyhow::Result<()> { - let mut ssk = crate::protocol::SSk::random(); - let mut spk = crate::protocol::SPk::random(); - StaticKem::keygen(ssk.secret_mut(), spk.deref_mut())?; + let mut ssk = crate::protocol::basic_types::SSk::random(); + let mut spk = crate::protocol::basic_types::SPk::random(); + StaticKem.keygen(ssk.secret_mut(), spk.deref_mut())?; ssk.store_secret(secret_key)?; spk.store(public_key) } diff --git a/rosenpass/src/config.rs b/rosenpass/src/config.rs index fedddeb1..a4f494b8 100644 --- a/rosenpass/src/config.rs +++ b/rosenpass/src/config.rs @@ -7,20 +7,19 @@ //! - TODO: support `~` in //! - TODO: provide tooling to create config file from shell -use crate::protocol::{SPk, SSk}; -use rosenpass_util::file::LoadValue; -use std::{ - collections::HashSet, - fs, - io::Write, - net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, - path::{Path, PathBuf}, -}; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::{collections::HashSet, fs, io::Write}; use anyhow::{bail, ensure}; -use rosenpass_util::file::{fopen_w, Visibility}; + use serde::{Deserialize, Serialize}; +use rosenpass_util::file::{fopen_w, LoadValue, Visibility}; + +use crate::protocol::basic_types::{SPk, SSk}; +use crate::protocol::osk_domain_separator::OskDomainSeparator; + use crate::app_server::AppServer; #[cfg(feature = "experiment_api")] @@ -36,6 +35,7 @@ fn empty_api_config() -> crate::api::config::ApiConfig { /// /// i.e. configuration for the `rosenpass exchange` and `rosenpass exchange-config` commands #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] pub struct Rosenpass { // TODO: Raise error if secret key or public key alone is set during deserialization // SEE: https://github.com/serde-rs/serde/issues/2793 @@ -77,6 +77,7 @@ pub struct Rosenpass { /// Public key and secret key locations. #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] +#[serde(deny_unknown_fields)] pub struct Keypair { /// path to the public key file pub public_key: PathBuf, @@ -104,13 +105,24 @@ impl Keypair { /// /// - TODO: replace this type with [`log::LevelFilter`], also see #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Copy, Clone)] +#[serde(deny_unknown_fields)] pub enum Verbosity { Quiet, Verbose, } +/// The protocol version to be used by a peer. +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Copy, Clone, Default)] +#[serde(deny_unknown_fields)] +pub enum ProtocolVersion { + #[default] + V02, + V03, +} + /// Configuration data for a single Rosenpass peer #[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct RosenpassPeer { /// path to the public key of the peer pub public_key: PathBuf, @@ -138,10 +150,82 @@ pub struct RosenpassPeer { /// Information for supplying exchanged keys directly to WireGuard #[serde(flatten)] pub wg: Option, + + #[serde(default)] + /// The protocol version to use for the exchange + pub protocol_version: ProtocolVersion, + + /// Allows using a custom domain separator + #[serde(flatten)] + pub osk_domain_separator: RosenpassPeerOskDomainSeparator, +} + +/// Configuration for [crate::protocol::osk_domain_separator::OskDomainSeparator] +/// +/// Refer to its documentation for more information and examples of how to use this. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RosenpassPeerOskDomainSeparator { + /// If Rosenpass is used for purposes other then securing WireGuard, + /// a custom domain separator and domain separator must be specified. + /// + /// Use `osk_organization` to indicate the organization who specifies the use case + /// and `osk_label` for a specific purpose within that organization. + /// + /// ```toml + /// [[peer]] + /// public_key = "my_public_key" + /// ... + /// osk_organization = "myorg.com" + /// osk_label = ["My Custom Messenger app"] + /// ``` + pub osk_organization: Option, + // If Rosenpass is used for purposes other then securing WireGuard, + /// a custom domain separator and domain separator must be specified. + /// + /// Use `osk_organization` to indicate the organization who specifies the use case + /// and `osk_label` for a specific purpose within that organization. + /// + /// ```toml + /// [[peer]] + /// public_key = "my_public_key" + /// ... + /// osk_namespace = "myorg.com" + /// osk_label = ["My Custom Messenger app"] + /// ``` + pub osk_label: Option>, +} + +impl RosenpassPeerOskDomainSeparator { + pub fn org_and_label(&self) -> anyhow::Result)>> { + match (&self.osk_organization, &self.osk_label) { + (None, None) => Ok(None), + (Some(org), Some(label)) => Ok(Some((&org, &label))), + (Some(_), None) => bail!("Specified osk_organization but not osk_label in config file. You need to specify both, or none."), + (None, Some(_)) => bail!("Specified osk_label but not osk_organization in config file. You need to specify both, or none."), + } + } + + pub fn validate(&self) -> anyhow::Result<()> { + let _org_and_label: Option<(_, _)> = self.org_and_label()?; + Ok(()) + } +} + +impl TryFrom for OskDomainSeparator { + type Error = anyhow::Error; + + fn try_from(val: RosenpassPeerOskDomainSeparator) -> anyhow::Result { + match val.org_and_label()? { + None => Ok(OskDomainSeparator::default()), + Some((org, label)) => Ok(OskDomainSeparator::custom_utf8(org, label)), + } + } } /// Information for supplying exchanged keys directly to WireGuard #[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct WireGuard { /// Name of the WireGuard interface to supply with pre-shared keys generated by the Rosenpass /// key exchange @@ -280,7 +364,7 @@ impl Rosenpass { // check the secret-key file is a valid key ensure!( SSk::load(&keypair.secret_key).is_ok(), - "could not load public-key file {:?}: invalid key", + "could not load secret-key file {:?}: invalid key", keypair.secret_key ); } @@ -325,6 +409,10 @@ impl Rosenpass { ); } } + + if let Err(e) = peer.osk_domain_separator.validate() { + bail!("Invalid OSK domain separation configuration for peer {i}: {e}"); + } } Ok(()) @@ -770,6 +858,53 @@ mod test { Ok(()) } + #[test] + fn test_protocol_version() { + let mut rosenpass = Rosenpass::empty(); + let mut peer_v_02 = RosenpassPeer::default(); + peer_v_02.protocol_version = ProtocolVersion::V02; + rosenpass.peers.push(peer_v_02); + let mut peer_v_03 = RosenpassPeer::default(); + peer_v_03.protocol_version = ProtocolVersion::V03; + rosenpass.peers.push(peer_v_03); + #[cfg(feature = "experiment_api")] + { + rosenpass.api.listen_fd = vec![]; + rosenpass.api.listen_path = vec![]; + rosenpass.api.stream_fd = vec![]; + } + #[cfg(feature = "experiment_api")] + let expected_toml = r#"listen = [] + verbosity = "Quiet" + + [api] + listen_fd = [] + listen_path = [] + stream_fd = [] + + [[peers]] + protocol_version = "V02" + public_key = "" + + [[peers]] + protocol_version = "V03" + public_key = "" + "#; + #[cfg(not(feature = "experiment_api"))] + let expected_toml = r#"listen = [] + verbosity = "Quiet" + + [[peers]] + protocol_version = "V02" + public_key = "" + + [[peers]] + protocol_version = "V03" + public_key = "" + "#; + assert_toml_round(rosenpass, expected_toml).unwrap() + } + #[test] fn test_cli_parse_multiple_peers() { let args = split_str( diff --git a/rosenpass/src/hash_domains.rs b/rosenpass/src/hash_domains.rs index b37981b6..cc0333b1 100644 --- a/rosenpass/src/hash_domains.rs +++ b/rosenpass/src/hash_domains.rs @@ -13,6 +13,8 @@ //! use rosenpass::{hash_domain, hash_domain_ns}; //! use rosenpass::hash_domains::protocol; //! +//! use rosenpass_ciphers::subtle::keyed_hash::KeyedHash; +//! //! // Declaring a custom hash domain //! hash_domain_ns!(protocol, custom_domain, "my custom hash domain label"); //! @@ -26,15 +28,18 @@ //! hash_domain!(domain_separators, sep1, "1"); //! hash_domain!(domain_separators, sep2, "2"); //! +//! // We use the SHAKE256 hash function for this example +//! let hash_choice = KeyedHash::keyed_shake256(); +//! //! // Generating values under hasher1 with both domain separators -//! let h1 = hasher1()?.mix(b"some data")?.dup(); -//! let h1v1 = h1.mix(&sep1()?)?.mix(b"More data")?.into_value(); -//! let h1v2 = h1.mix(&sep2()?)?.mix(b"More data")?.into_value(); +//! let h1 = hasher1(hash_choice.clone())?.mix(b"some data")?.dup(); +//! let h1v1 = h1.mix(&sep1(hash_choice.clone())?)?.mix(b"More data")?.into_value(); +//! let h1v2 = h1.mix(&sep2(hash_choice.clone())?)?.mix(b"More data")?.into_value(); //! //! // Generating values under hasher2 with both domain separators -//! let h2 = hasher2()?.mix(b"some data")?.dup(); -//! let h2v1 = h2.mix(&sep1()?)?.mix(b"More data")?.into_value(); -//! let h2v2 = h2.mix(&sep2()?)?.mix(b"More data")?.into_value(); +//! let h2 = hasher2(hash_choice.clone())?.mix(b"some data")?.dup(); +//! let h2v1 = h2.mix(&sep1(hash_choice.clone())?)?.mix(b"More data")?.into_value(); +//! let h2v2 = h2.mix(&sep2(hash_choice.clone())?)?.mix(b"More data")?.into_value(); //! //! // All of the domain separators are now different, random strings //! let values = [h1v1, h1v2, h2v1, h2v2]; @@ -49,6 +54,7 @@ use anyhow::Result; use rosenpass_ciphers::hash_domain::HashDomain; +use rosenpass_ciphers::subtle::keyed_hash::KeyedHash; /// Declare a hash function /// @@ -62,8 +68,8 @@ use rosenpass_ciphers::hash_domain::HashDomain; macro_rules! hash_domain_ns { ($(#[$($attrss:tt)*])* $base:ident, $name:ident, $($lbl:expr),+ ) => { $(#[$($attrss)*])* - pub fn $name() -> ::anyhow::Result<::rosenpass_ciphers::hash_domain::HashDomain> { - let t = $base()?; + pub fn $name(hash_choice: KeyedHash) -> ::anyhow::Result<::rosenpass_ciphers::hash_domain::HashDomain> { + let t = $base(hash_choice)?; $( let t = t.mix($lbl.as_bytes())?; )* Ok(t) } @@ -81,8 +87,8 @@ macro_rules! hash_domain_ns { macro_rules! hash_domain { ($(#[$($attrss:tt)*])* $base:ident, $name:ident, $($lbl:expr),+ ) => { $(#[$($attrss)*])* - pub fn $name() -> ::anyhow::Result<[u8; ::rosenpass_ciphers::KEY_LEN]> { - let t = $base()?; + pub fn $name(hash_choice: KeyedHash) -> ::anyhow::Result<[u8; ::rosenpass_ciphers::KEY_LEN]> { + let t = $base(hash_choice)?; $( let t = t.mix($lbl.as_bytes())?; )* Ok(t.into_value()) } @@ -94,15 +100,22 @@ macro_rules! hash_domain { /// This serves as a global [domain separator](https://en.wikipedia.org/wiki/Domain_separation) /// used in various places in the rosenpass protocol. /// -/// This is generally used to create further hash-domains for specific purposes. See +/// This is generally used to create further hash-domains for specific purposes. Depending on +/// the used hash function, the protocol string is different. /// /// # Examples /// /// See the source file for details about how this is used concretely. /// /// See the [module](self) documentation on how to use the hash domains in general -pub fn protocol() -> Result { - HashDomain::zero().mix("Rosenpass v1 mceliece460896 Kyber512 ChaChaPoly1305 BLAKE2s".as_bytes()) +pub fn protocol(hash_choice: KeyedHash) -> Result { + // Depending on the hash function, we use different protocol strings + match hash_choice { + KeyedHash::KeyedShake256(_) => HashDomain::zero(hash_choice) + .mix("Rosenpass v1 mceliece460896 Kyber512 ChaChaPoly1305 SHAKE256".as_bytes()), + KeyedHash::IncorrectHmacBlake2b(_) => HashDomain::zero(hash_choice) + .mix("Rosenpass v1 mceliece460896 Kyber512 ChaChaPoly1305 BLAKE2s".as_bytes()), + } } hash_domain_ns!( @@ -282,25 +295,21 @@ hash_domain_ns!( /// We do recommend that third parties base their specific domain separators /// on a internet domain and/or mix in much more specific information. /// - /// We only really use this to derive a output key for wireguard; see [osk]. - /// /// See [_ckextract]. /// /// # Examples /// /// See the [module](self) documentation on how to use the hash domains in general. - _ckextract, _user, "user"); + _ckextract, cke_user, "user"); hash_domain_ns!( /// Chaining key domain separator for any rosenpass specific purposes. /// - /// We only really use this to derive a output key for wireguard; see [osk]. - /// /// See [_ckextract]. /// /// # Examples /// /// See the [module](self) documentation on how to use the hash domains in general. - _user, _rp, "rosenpass.eu"); + cke_user, cke_user_rosenpass, "rosenpass.eu"); hash_domain!( /// Chaining key domain separator for deriving the key sent to WireGuard. /// @@ -312,4 +321,4 @@ hash_domain!( /// Check out its source code! /// /// See the [module](self) documentation on how to use the hash domains in general. - _rp, osk, "wireguard psk"); + cke_user_rosenpass, ext_wireguard_psk_osk, "wireguard psk"); diff --git a/rosenpass/src/msgs.rs b/rosenpass/src/msgs.rs index fd281c60..f6ea1b6f 100644 --- a/rosenpass/src/msgs.rs +++ b/rosenpass/src/msgs.rs @@ -9,13 +9,12 @@ //! To achieve this we utilize the zerocopy library. //! use std::mem::size_of; -use std::u8; use zerocopy::{AsBytes, FromBytes, FromZeroes}; use super::RosenpassError; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::{EphemeralKem, StaticKem}; -use rosenpass_ciphers::{aead, xaead, KEY_LEN}; +use rosenpass_cipher_traits::primitives::{Aead as _, Kem}; +use rosenpass_ciphers::{Aead, XAead, KEY_LEN}; +use rosenpass_ciphers::{EphemeralKem, StaticKem}; /// Length of a session ID such as [InitHello::sidi] pub const SESSION_ID_LEN: usize = 4; @@ -32,7 +31,7 @@ pub const MAX_MESSAGE_LEN: usize = 2500; // TODO fix this pub const BISCUIT_PT_LEN: usize = size_of::(); /// Length in bytes of an encrypted Biscuit (cipher text) -pub const BISCUIT_CT_LEN: usize = BISCUIT_PT_LEN + xaead::NONCE_LEN + xaead::TAG_LEN; +pub const BISCUIT_CT_LEN: usize = BISCUIT_PT_LEN + XAead::NONCE_LEN + XAead::TAG_LEN; /// Size of the field [Envelope::mac] pub const MAC_SIZE: usize = 16; @@ -136,9 +135,9 @@ pub struct InitHello { /// Classic McEliece Ciphertext pub sctr: [u8; StaticKem::CT_LEN], /// Encryped: 16 byte hash of McEliece initiator static key - pub pidic: [u8; aead::TAG_LEN + 32], + pub pidic: [u8; Aead::TAG_LEN + 32], /// Encrypted TAI64N Time Stamp (against replay attacks) - pub auth: [u8; aead::TAG_LEN], + pub auth: [u8; Aead::TAG_LEN], } /// This is the second message sent by the responder to the initiator @@ -187,7 +186,7 @@ pub struct RespHello { /// Classic McEliece Ciphertext pub scti: [u8; StaticKem::CT_LEN], /// Empty encrypted message (just an auth tag) - pub auth: [u8; aead::TAG_LEN], + pub auth: [u8; Aead::TAG_LEN], /// Responders handshake state in encrypted form pub biscuit: [u8; BISCUIT_CT_LEN], } @@ -236,7 +235,7 @@ pub struct InitConf { /// Responders handshake state in encrypted form pub biscuit: [u8; BISCUIT_CT_LEN], /// Empty encrypted message (just an auth tag) - pub auth: [u8; aead::TAG_LEN], + pub auth: [u8; Aead::TAG_LEN], } /// This is the fourth message sent by the initiator to the responder @@ -292,7 +291,7 @@ pub struct EmptyData { /// Nonce pub ctr: [u8; 8], /// Empty encrypted message (just an auth tag) - pub auth: [u8; aead::TAG_LEN], + pub auth: [u8; Aead::TAG_LEN], } /// Cookie encrypted and sent to the initiator by the responder in [RespHello] @@ -346,7 +345,7 @@ pub struct CookieReplyInner { /// Session ID of the sender (initiator) pub sid: [u8; 4], /// Encrypted cookie with authenticated initiator `mac` - pub cookie_encrypted: [u8; xaead::NONCE_LEN + COOKIE_SIZE + xaead::TAG_LEN], + pub cookie_encrypted: [u8; XAead::NONCE_LEN + COOKIE_SIZE + XAead::TAG_LEN], } /// Specialized message for use in the cookie mechanism. @@ -437,7 +436,8 @@ impl From for u8 { #[cfg(test)] mod test_constants { use crate::msgs::{BISCUIT_CT_LEN, BISCUIT_PT_LEN}; - use rosenpass_ciphers::{xaead, KEY_LEN}; + use rosenpass_cipher_traits::primitives::Aead as _; + use rosenpass_ciphers::{XAead, KEY_LEN}; #[test] fn sodium_keysize() { @@ -453,7 +453,7 @@ mod test_constants { fn biscuit_ct_len() { assert_eq!( BISCUIT_CT_LEN, - BISCUIT_PT_LEN + xaead::NONCE_LEN + xaead::TAG_LEN + BISCUIT_PT_LEN + XAead::NONCE_LEN + XAead::TAG_LEN ); } } diff --git a/rosenpass/src/protocol/basic_types.rs b/rosenpass/src/protocol/basic_types.rs new file mode 100644 index 00000000..00078ac6 --- /dev/null +++ b/rosenpass/src/protocol/basic_types.rs @@ -0,0 +1,38 @@ +//! Key types and other fundamental types used in the Rosenpass protocol + +use rosenpass_cipher_traits::primitives::{Aead, Kem}; +use rosenpass_ciphers::{EphemeralKem, StaticKem, XAead, KEY_LEN}; +use rosenpass_secret_memory::{Public, PublicBox, Secret}; + +use crate::msgs::{BISCUIT_ID_LEN, MAX_MESSAGE_LEN, SESSION_ID_LEN}; + +/// Static public key +/// +/// Using [PublicBox] instead of [Public] because Classic McEliece keys are very large. +pub type SPk = PublicBox<{ StaticKem::PK_LEN }>; +/// Static secret key +pub type SSk = Secret<{ StaticKem::SK_LEN }>; +/// Ephemeral public key +pub type EPk = Public<{ EphemeralKem::PK_LEN }>; +pub type ESk = Secret<{ EphemeralKem::SK_LEN }>; + +/// Symmetric key +pub type SymKey = Secret; +/// Variant of [SymKey] for use cases where the value is public +pub type PublicSymKey = [u8; 32]; + +/// Peer ID (derived from the public key, see the hash derivations in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)) +pub type PeerId = Public; +/// Session ID +pub type SessionId = Public; +/// Biscuit ID +pub type BiscuitId = Public; + +/// Nonce for use with random-nonce AEAD +pub type XAEADNonce = Public<{ XAead::NONCE_LEN }>; + +/// Buffer capably of holding any Rosenpass protocol message +pub type MsgBuf = Public; + +/// Server-local peer number; this is just the index in [super::CryptoServer::peers] +pub type PeerNo = usize; diff --git a/rosenpass/src/protocol/build_crypto_server.rs b/rosenpass/src/protocol/build_crypto_server.rs index fd4cce96..7929a47d 100644 --- a/rosenpass/src/protocol/build_crypto_server.rs +++ b/rosenpass/src/protocol/build_crypto_server.rs @@ -1,11 +1,13 @@ -use rosenpass_util::{ - build::Build, - mem::{DiscardResultExt, SwapWithDefaultExt}, - result::ensure_or, -}; use thiserror::Error; -use super::{CryptoServer, PeerPtr, SPk, SSk, SymKey}; +use rosenpass_util::mem::{DiscardResultExt, SwapWithDefaultExt}; +use rosenpass_util::{build::Build, result::ensure_or}; + +use crate::config::ProtocolVersion; + +use super::basic_types::{SPk, SSk, SymKey}; +use super::osk_domain_separator::OskDomainSeparator; +use super::{CryptoServer, PeerPtr}; #[derive(Debug, Clone)] /// A pair of matching public/secret keys used to launch the crypto server. @@ -47,7 +49,8 @@ impl Keypair { /// # Example /// /// ```rust - /// use rosenpass::protocol::{Keypair, SSk, SPk}; + /// use rosenpass::protocol::basic_types::{SSk, SPk}; + /// use rosenpass::protocol::Keypair; /// /// // We have to define the security policy before using Secrets. /// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; @@ -66,12 +69,13 @@ impl Keypair { /// Creates a new "empty" key pair. All bytes are initialized to zero. /// - /// See [SSk:zero()][crate::protocol::SSk::zero] and [SPk:zero()][crate::protocol::SPk::zero], respectively. + /// See [SSk:zero()][SSk::zero] and [SPk:zero()][SPk::zero], respectively. /// /// # Example /// /// ```rust - /// use rosenpass::protocol::{Keypair, SSk, SPk}; + /// use rosenpass::protocol::basic_types::{SSk, SPk}; + /// use rosenpass::protocol::Keypair; /// /// // We have to define the security policy before using Secrets. /// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; @@ -90,7 +94,7 @@ impl Keypair { /// Creates a new (securely-)random key pair. The mechanism is described in [rosenpass_secret_memory::Secret]. /// - /// See [SSk:random()][crate::protocol::SSk::random] and [SPk:random()][crate::protocol::SPk::random], respectively. + /// See [SSk:random()][SSk::random] and [SPk:random()][SPk::random], respectively. pub fn random() -> Self { Self::new(SSk::random(), SPk::random()) } @@ -127,7 +131,7 @@ pub struct MissingKeypair; /// /// There are multiple ways of creating a crypto server: /// -/// 1. Provide the key pair at initialization time (using [CryptoServer::new][crate::protocol::CryptoServer::new]) +/// 1. Provide the key pair at initialization time (using [CryptoServer::new][CryptoServer::new]) /// 2. Provide the key pair at a later time (using [BuildCryptoServer::empty]) /// /// With BuildCryptoServer, you can gradually configure parameters as they become available. @@ -145,18 +149,23 @@ pub struct MissingKeypair; /// /// ```rust /// use rosenpass_util::build::Build; -/// use rosenpass::protocol::{BuildCryptoServer, Keypair, PeerParams, SPk, SymKey}; +/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; +/// +/// use rosenpass::config::ProtocolVersion; +/// +/// use rosenpass::protocol::basic_types::{SPk, SymKey}; +/// use rosenpass::protocol::{BuildCryptoServer, Keypair, PeerParams}; +/// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; /// /// // We have to define the security policy before using Secrets. -/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; /// secret_policy_use_only_malloc_secrets(); /// /// let keypair = Keypair::random(); -/// let peer1 = PeerParams { psk: Some(SymKey::random()), pk: SPk::random() }; -/// let peer2 = PeerParams { psk: None, pk: SPk::random() }; +/// let peer1 = PeerParams { psk: Some(SymKey::random()), pk: SPk::random(), protocol_version: ProtocolVersion::V02, osk_domain_separator: OskDomainSeparator::default() }; +/// let peer2 = PeerParams { psk: None, pk: SPk::random(), protocol_version: ProtocolVersion::V02, osk_domain_separator: OskDomainSeparator::default() }; /// /// let mut builder = BuildCryptoServer::new(Some(keypair.clone()), vec![peer1]); -/// builder.add_peer(peer2.psk.clone(), peer2.pk); +/// builder.add_peer(peer2.psk.clone(), peer2.pk, ProtocolVersion::V02, OskDomainSeparator::default()); /// /// let server = builder.build().expect("build failed"); /// assert_eq!(server.peers.len(), 2); @@ -186,8 +195,17 @@ impl Build for BuildCryptoServer { let mut srv = CryptoServer::new(sk, pk); - for (idx, PeerParams { psk, pk }) in self.peers.into_iter().enumerate() { - let PeerPtr(idx2) = srv.add_peer(psk, pk)?; + for (idx, params) in self.peers.into_iter().enumerate() { + let PeerParams { + psk, + pk, + protocol_version, + osk_domain_separator, + } = params; + + let PeerPtr(idx2) = + srv.add_peer(psk, pk, protocol_version.into(), osk_domain_separator)?; + assert!(idx == idx2, "Peer id changed during CryptoServer construction from {idx} to {idx2}. This is a developer error.") } @@ -196,18 +214,21 @@ impl Build for BuildCryptoServer { } #[derive(Debug)] -/// Cryptographic key(s) identifying the connected [peer][crate::protocol::Peer] ("client") +/// Cryptographic key(s) identifying the connected [peer][super::Peer] ("client") /// for a given session that is being managed by the crypto server. /// -/// Each peer must be identified by a [public key (SPk)][crate::protocol::SPk]. -/// Optionally, a [symmetric key (SymKey)][crate::protocol::SymKey] +/// Each peer must be identified by a [public key (SPk)][SPk]. +/// Optionally, a [symmetric key (SymKey)][SymKey] /// can be provided when setting up the connection. -/// For more information on the intended usage and security considerations, see [Peer::psk][crate::protocol::Peer::psk] and [Peer::spkt][crate::protocol::Peer::spkt]. +/// For more information on the intended usage and security considerations, see [Peer::psk][super::Peer::psk] and [Peer::spkt][super::Peer::spkt]. pub struct PeerParams { /// Pre-shared (symmetric) encryption keys that should be used with this peer. pub psk: Option, /// Public key identifying the peer. pub pk: SPk, + /// The used protocol version. + pub protocol_version: ProtocolVersion, + pub osk_domain_separator: OskDomainSeparator, } impl BuildCryptoServer { @@ -305,13 +326,17 @@ impl BuildCryptoServer { /// Adding peers to an existing builder: /// /// ```rust + /// use rosenpass::config::ProtocolVersion; + /// + /// use rosenpass_util::build::Build; + /// use rosenpass::protocol::basic_types::{SymKey, SPk}; + /// use rosenpass::protocol::{BuildCryptoServer, Keypair}; + /// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; + /// /// // We have to define the security policy before using Secrets. /// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; /// secret_policy_use_only_malloc_secrets(); /// - /// use rosenpass_util::build::Build; - /// use rosenpass::protocol::{BuildCryptoServer, Keypair, SymKey, SPk}; - /// /// // Deferred initialization: Create builder first, add some peers later /// let keypair_option = Some(Keypair::random()); /// let mut builder = BuildCryptoServer::new(keypair_option, Vec::new()); @@ -323,7 +348,7 @@ impl BuildCryptoServer { /// // Now we've found a peer that should be added to the configuration /// let pre_shared_key = SymKey::random(); /// let public_key = SPk::random(); - /// builder.with_added_peer(Some(pre_shared_key.clone()), public_key.clone()); + /// builder.with_added_peer(Some(pre_shared_key.clone()), public_key.clone(), ProtocolVersion::V02, OskDomainSeparator::default()); /// /// // New server instances will then start with the peer being registered already /// let server = builder.build().expect("build failed"); @@ -333,16 +358,33 @@ impl BuildCryptoServer { /// assert_eq!(peer.spkt, public_key); /// assert_eq!(peer_psk.secret(), pre_shared_key.secret()); /// ``` - pub fn with_added_peer(&mut self, psk: Option, pk: SPk) -> &mut Self { + pub fn with_added_peer( + &mut self, + psk: Option, + pk: SPk, + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, + ) -> &mut Self { // TODO: Check here already whether peer was already added - self.peers.push(PeerParams { psk, pk }); + self.peers.push(PeerParams { + psk, + pk, + protocol_version, + osk_domain_separator, + }); self } /// Add a new entry to the list of registered peers, with or without a pre-shared key. - pub fn add_peer(&mut self, psk: Option, pk: SPk) -> PeerPtr { + pub fn add_peer( + &mut self, + psk: Option, + pk: SPk, + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, + ) -> PeerPtr { let id = PeerPtr(self.peers.len()); - self.with_added_peer(psk, pk); + self.with_added_peer(psk, pk, protocol_version, osk_domain_separator); id } @@ -355,17 +397,23 @@ impl BuildCryptoServer { /// Extracting the server configuration from a builder: /// /// ```rust - /// // We have to define the security policy before using Secrets. - /// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; - /// secret_policy_use_only_malloc_secrets(); - /// /// use rosenpass_util::build::Build; - /// use rosenpass::protocol::{BuildCryptoServer, Keypair, SymKey, SPk}; + /// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets; + /// + /// use rosenpass::config::ProtocolVersion; + /// use rosenpass::hash_domains::protocol; + /// + /// use rosenpass::protocol::basic_types::{SymKey, SPk}; + /// use rosenpass::protocol::{BuildCryptoServer, Keypair}; + /// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; + /// + /// // We have to define the security policy before using Secrets. + /// secret_policy_use_only_malloc_secrets(); /// /// let keypair = Keypair::random(); /// let peer_pk = SPk::random(); /// let mut builder = BuildCryptoServer::new(Some(keypair.clone()), vec![]); - /// builder.add_peer(None, peer_pk); + /// builder.add_peer(None, peer_pk, ProtocolVersion::V02, OskDomainSeparator::default()); /// /// // Extract configuration parameters from the decomissioned builder /// let (keypair_option, peers) = builder.take_parts(); diff --git a/rosenpass/src/protocol/constants.rs b/rosenpass/src/protocol/constants.rs new file mode 100644 index 00000000..8478cdd9 --- /dev/null +++ b/rosenpass/src/protocol/constants.rs @@ -0,0 +1,64 @@ +//! Constants and configuration values used in the rosenpass core protocol + +use crate::msgs::MAC_SIZE; + +use super::timing::Timing; + +/// Time after which the responder attempts to rekey the session +/// +/// From the wireguard paper: rekey every two minutes, +/// discard the key if no rekey is achieved within three +pub const REKEY_AFTER_TIME_RESPONDER: Timing = 120.0; +/// Time after which the initiator attempts to rekey the session. +/// +/// This happens ten seconds after [REKEY_AFTER_TIME_RESPONDER], so +/// parties would usually switch roles after every handshake. +/// +/// From the wireguard paper: rekey every two minutes, +/// discard the key if no rekey is achieved within three +pub const REKEY_AFTER_TIME_INITIATOR: Timing = 130.0; +/// Time after which either party rejects the current key. +/// +/// At this point a new key should have been negotiated. +/// +/// Rejection happens 50-60 seconds after key renegotiation +/// to allow for a graceful handover. +/// From the wireguard paper: rekey every two minutes, +/// discard the key if no rekey is achieved within three +pub const REJECT_AFTER_TIME: Timing = 180.0; + +/// The length of the `cookie_secret` in the [whitepaper](https://rosenpass.eu/whitepaper.pdf) +pub const COOKIE_SECRET_LEN: usize = MAC_SIZE; +/// The life time of the `cookie_secret` in the [whitepaper](https://rosenpass.eu/whitepaper.pdf) +pub const COOKIE_SECRET_EPOCH: Timing = 120.0; + +/// Length of a cookie value (see info about the cookie mechanism in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)) +pub const COOKIE_VALUE_LEN: usize = MAC_SIZE; +/// Time after which to delete a cookie, as the initiator, for a certain peer (see info about the cookie mechanism in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)) +pub const PEER_COOKIE_VALUE_EPOCH: Timing = 120.0; + +/// Seconds until the biscuit key is changed; we issue biscuits +/// using one biscuit key for one epoch and store the biscuit for +/// decryption for a second epoch +/// +/// The biscuit mechanism is used to make sure the responder is stateless in our protocol. +pub const BISCUIT_EPOCH: Timing = 300.0; + +/// The initiator opportunistically retransmits their messages; it applies an increasing delay +/// between each retreansmission. This is the factor by which the delay grows after each +/// retransmission. +pub const RETRANSMIT_DELAY_GROWTH: Timing = 2.0; +/// The initiator opportunistically retransmits their messages; it applies an increasing delay +/// between each retreansmission. This is the initial delay between retransmissions. +pub const RETRANSMIT_DELAY_BEGIN: Timing = 0.5; +/// The initiator opportunistically retransmits their messages; it applies an increasing delay +/// between each retreansmission. This is the maximum delay between retransmissions. +pub const RETRANSMIT_DELAY_END: Timing = 10.0; +/// The initiator opportunistically retransmits their messages; it applies an increasing delay +/// between each retreansmission. This is the jitter (randomness) applied to the retransmission +/// delay. +pub const RETRANSMIT_DELAY_JITTER: Timing = 0.5; + +/// This is the maximum delay that can separate two events for us to consider the events to have +/// happened at the same time. +pub const EVENT_GRACE: Timing = 0.0025; diff --git a/rosenpass/src/protocol/cookies.rs b/rosenpass/src/protocol/cookies.rs new file mode 100644 index 00000000..b3c54139 --- /dev/null +++ b/rosenpass/src/protocol/cookies.rs @@ -0,0 +1,98 @@ +//! Cryptographic key management for cookies and biscuits used in the protocol +//! +//! Cookies in general are conceptually similar to browser cookies; +//! i.e. mechanisms to store information in the party connected to via network. +//! +//! In our case specifically we refer to any mechanisms in the Rosenpass protocol +//! where a peer stores some information in the other party that is cryptographically +//! protected using a temporary, randomly generated key. This file contains the mechanisms +//! used to store the secret keys. +//! +//! We have two cookie-mechanisms in particular: +//! +//! - Rosenpass "biscuits" — the mechanism used to make sure the Rosenpass protocol is stateless +//! with respect to the responder +//! - WireGuard's cookie mechanism to enable proof of IP ownership; Rosenpass has experimental +//! support for this mechanism +//! +//! The CookieStore type is also used to store cookie secrets sent from the responder to the +//! initiator. This is a bad design and we should separate out this functionality. +//! +//! TODO: CookieStore should not be used for cookie secrets sent from responder to initiator. +//! TODO: Move cookie lifetime management functionality into here + +use rosenpass_ciphers::KEY_LEN; +use rosenpass_secret_memory::Secret; + +use super::{constants::COOKIE_SECRET_LEN, timing::Timing}; + +/// Container for storing cookie secrets like [BiscuitKey] or [CookieSecret]. +/// +/// This is really just a secret key and a time stamp of creation. Concrete +/// usages (such as for the biscuit key) impose a time limit about how long +/// a key can be used and the time of creation is used to impose that time limit. +/// +/// # Examples +/// +/// ``` +/// use rosenpass_util::time::Timebase; +/// use rosenpass::protocol::{timing::BCE, basic_types::SymKey, cookies::CookieStore}; +/// +/// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); +/// +/// let fixed_secret = SymKey::random(); +/// let timebase = Timebase::default(); +/// +/// let mut store = CookieStore::<32>::new(); +/// assert_ne!(store.value.secret(), SymKey::zero().secret()); +/// assert_eq!(store.created_at, BCE); +/// +/// let time_before_call = timebase.now(); +/// store.update(&timebase, fixed_secret.secret()); +/// assert_eq!(store.value.secret(), fixed_secret.secret()); +/// assert!(store.created_at < timebase.now()); +/// assert!(store.created_at > time_before_call); +/// +/// // Same as new() +/// store.erase(); +/// assert_ne!(store.value.secret(), SymKey::zero().secret()); +/// assert_eq!(store.created_at, BCE); +/// +/// let secret_before_call = store.value.clone(); +/// let time_before_call = timebase.now(); +/// store.randomize(&timebase); +/// assert_ne!(store.value.secret(), secret_before_call.secret()); +/// assert!(store.created_at < timebase.now()); +/// assert!(store.created_at > time_before_call); +/// ``` +#[derive(Debug)] +pub struct CookieStore { + /// Time of creation of the secret key + pub created_at: Timing, + /// The secret key + pub value: Secret, +} + +/// Stores cookie secret, which is used to create a rotating the cookie value +/// +/// Concrete value is in [super::CryptoServer::cookie_secrets]. +/// +/// The pointer type is [super::ServerCookieSecretPtr]. +pub type CookieSecret = CookieStore; + +/// Storage for our biscuit keys. +/// +/// The biscuit keys encrypt what we call "biscuits". +/// These biscuits contain the responder state for a particular handshake. By moving +/// state into these biscuits, we make sure the responder is stateless. +/// +/// A Biscuit is like a fancy cookie. To avoid state disruption attacks, +/// the responder doesn't store state. Instead the state is stored in a +/// Biscuit, that is encrypted using the [BiscuitKey] which is only known to +/// the Responder. Thus secrecy of the Responder state is not violated, still +/// the responder can avoid storing this state. +/// +/// Concrete value is in [super::CryptoServer::biscuit_keys]. +/// +/// The pointer type is [super::BiscuitKeyPtr]. +pub type BiscuitKey = CookieStore; diff --git a/rosenpass/src/protocol/index.rs b/rosenpass/src/protocol/index.rs new file mode 100644 index 00000000..9f3556be --- /dev/null +++ b/rosenpass/src/protocol/index.rs @@ -0,0 +1,45 @@ +//! Quick lookup of values in [super::CryptoServer] + +use std::collections::HashMap; + +use super::basic_types::{PeerId, PeerNo, SessionId}; +use super::KnownResponseHash; + +/// Maps various keys to peer (numbers). +/// +/// See: +/// - [super::CryptoServer::index] +/// - [super::CryptoServer::peers] +/// - [PeerNo] +/// - [super::PeerPtr] +/// - [super::Peer] +pub type PeerIndex = HashMap; + +/// We maintain various indices in [super::CryptoServer::index], mapping some key to a particular +/// [PeerNo], i.e. to an index in [super::CryptoServer::peers]. These are the possible index key. +#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub enum PeerIndexKey { + /// Lookup of a particular peer given the [PeerId], i.e. a value derived from the peers public + /// key as created by [super::CryptoServer::pidm] or [super::Peer::pidt]. + /// + /// The peer id is used by the initiator to tell the responder about its identity in + /// [crate::msgs::InitHello]. + /// + /// See also the pointer types [super::PeerPtr]. + Peer(PeerId), + /// Lookup of a particular session id. + /// + /// This is used to look up both established sessions (see + /// [super::CryptoServer::lookup_session]) and ongoing handshakes (see [super::CryptoServer::lookup_handshake]). + /// + /// Lookup of a peer to get an established session or a handshake is sufficient, because a peer + /// contains a limited number of sessions and handshakes ([super::Peer::session] and [super::Peer::handshake] respectively). + /// + /// See also the pointer types [super::IniHsPtr] and [super::SessionPtr]. + Sid(SessionId), + /// Lookup of a cached response ([crate::msgs::Envelope]<[crate::msgs::EmptyData]>) to an [crate::msgs::InitConf] (i.e. + /// [crate::msgs::Envelope]<[crate::msgs::InitConf]>) message. + /// + /// See [super::KnownInitConfResponsePtr] on how this value is maintained. + KnownInitConfResponse(KnownResponseHash), +} diff --git a/rosenpass/src/protocol/mod.rs b/rosenpass/src/protocol/mod.rs index e8079308..7de618fe 100644 --- a/rosenpass/src/protocol/mod.rs +++ b/rosenpass/src/protocol/mod.rs @@ -24,24 +24,28 @@ //! //! ``` //! use std::ops::DerefMut; +//! //! use rosenpass_secret_memory::policy::*; -//! use rosenpass_cipher_traits::Kem; -//! use rosenpass_ciphers::kem::StaticKem; -//! use rosenpass::{ -//! protocol::{SSk, SPk, MsgBuf, PeerPtr, CryptoServer, SymKey}, -//! }; +//! use rosenpass_cipher_traits::primitives::Kem; +//! use rosenpass_ciphers::StaticKem; +//! +//! use rosenpass::protocol::basic_types::{SSk, SPk, MsgBuf, SymKey}; +//! use rosenpass::protocol::{PeerPtr, CryptoServer}; +//! use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; +//! //! # fn main() -> anyhow::Result<()> { //! // Set security policy for storing secrets //! +//! use rosenpass::protocol::ProtocolVersion; //! secret_policy_try_use_memfd_secrets(); //! //! // initialize secret and public key for peer a ... //! let (mut peer_a_sk, mut peer_a_pk) = (SSk::zero(), SPk::zero()); -//! StaticKem::keygen(peer_a_sk.secret_mut(), peer_a_pk.deref_mut())?; +//! StaticKem.keygen(peer_a_sk.secret_mut(), peer_a_pk.deref_mut())?; //! //! // ... and for peer b //! let (mut peer_b_sk, mut peer_b_pk) = (SSk::zero(), SPk::zero()); -//! StaticKem::keygen(peer_b_sk.secret_mut(), peer_b_pk.deref_mut())?; +//! StaticKem.keygen(peer_b_sk.secret_mut(), peer_b_pk.deref_mut())?; //! //! // initialize server and a pre-shared key //! let psk = SymKey::random(); @@ -49,8 +53,8 @@ //! let mut b = CryptoServer::new(peer_b_sk, peer_b_pk.clone()); //! //! // introduce peers to each other -//! a.add_peer(Some(psk.clone()), peer_b_pk)?; -//! b.add_peer(Some(psk), peer_a_pk)?; +//! a.add_peer(Some(psk.clone()), peer_b_pk, ProtocolVersion::V03, OskDomainSeparator::default())?; +//! b.add_peer(Some(psk), peer_a_pk, ProtocolVersion::V03, OskDomainSeparator::default())?; //! //! // declare buffers for message exchange //! let (mut a_buf, mut b_buf) = (MsgBuf::zero(), MsgBuf::zero()); @@ -75,8 +79,20 @@ //! ``` mod build_crypto_server; +pub use build_crypto_server::*; + +pub mod basic_types; +pub mod constants; +pub mod cookies; +pub mod index; +pub mod osk_domain_separator; +pub mod testutils; +pub mod timing; +pub mod zerocopy; + #[allow(clippy::module_inception)] mod protocol; - -pub use build_crypto_server::*; pub use protocol::*; + +#[cfg(test)] +mod test; diff --git a/rosenpass/src/protocol/osk_domain_separator.rs b/rosenpass/src/protocol/osk_domain_separator.rs new file mode 100644 index 00000000..e8f2b9ec --- /dev/null +++ b/rosenpass/src/protocol/osk_domain_separator.rs @@ -0,0 +1,91 @@ +//! Management of domain separators for the OSK (output key) in the rosenpass protocol +//! +//! The domain separator is there to ensure that keys are bound to the purpose they are used for. +//! +//! See the whitepaper section on protocol extensions for more details on how this is used. +//! +//! # See also +//! +//! - [crate::protocol::Peer] +//! - [crate::protocol::CryptoServer::add_peer] +//! - [crate::protocol::CryptoServer::osk] +//! +//! # Examples +//! +//! There are some basic examples of using custom domain separators in the examples of +//! [super::CryptoServer::poll]. Look for the test function `test_osk_label_mismatch()` +//! in particular. + +use rosenpass_ciphers::subtle::keyed_hash::KeyedHash; +use rosenpass_util::result::OkExt; + +use crate::hash_domains; + +use super::basic_types::PublicSymKey; + +/// The OSK (output shared key) domain separator to use for a specific peer +/// +#[derive(Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Default)] +pub enum OskDomainSeparator { + /// By default we use the domain separator that indicates that the resulting keys + /// are used by WireGuard to establish a connection + #[default] + ExtensionWireguardPsk, + /// Used for user-defined domain separators + Custom { + /// A globally unique string identifying the vendor or group who defines this domain + /// separator (we use our domain ourselves – "rosenpass.eu") + namespace: Vec, + /// Any custom labels within that namespace. Could be descriptive prose. + labels: Vec>, + }, +} + +impl OskDomainSeparator { + /// Construct [OskDomainSeparator::ExtensionWireguardPsk] + pub fn for_wireguard_psk() -> Self { + Self::ExtensionWireguardPsk + } + + /// Construct [OskDomainSeparator::Custom] from strings + pub fn custom_utf8(namespace: &str, label: I) -> Self + where + I: IntoIterator, + T: AsRef, + { + let namespace = namespace.as_bytes().to_owned(); + let labels = label + .into_iter() + .map(|e| e.as_ref().as_bytes().to_owned()) + .collect::>(); + Self::Custom { namespace, labels } + } + + /// Variant of [Self::custom_utf8] that takes just one label (instead of a sequence) + pub fn custom_utf8_single_label(namespace: &str, label: &str) -> Self { + Self::custom_utf8(namespace, std::iter::once(label)) + } + + /// The domain separator is not just an encoded string, it instead uses + /// [rosenpass_ciphers::hash_domain::HashDomain], starting from [hash_domains::cke_user]. + /// + /// This means, that the domain separator is really a sequence of multiple different domain + /// separators, each of which is allowed to be quite long. This is very useful as it allows + /// users to avoid specifying complex, prosaic domain separators. To ensure that this does not + /// force us create extra overhead when the protocol is executed, this sequence of strings is + /// compressed into a single, fixed-length hash of all the inputs. This hash could be created + /// at program startup and cached. + /// + /// This function generates this fixed-length hash. + pub fn compress_with(&self, hash_choice: KeyedHash) -> anyhow::Result { + use OskDomainSeparator as O; + match &self { + O::ExtensionWireguardPsk => hash_domains::ext_wireguard_psk_osk(hash_choice), + O::Custom { namespace, labels } => hash_domains::cke_user(hash_choice)? + .mix(namespace)? + .mix_many(labels)? + .into_value() + .ok(), + } + } +} diff --git a/rosenpass/src/protocol/protocol.rs b/rosenpass/src/protocol/protocol.rs index 52e48441..778a1bed 100644 --- a/rosenpass/src/protocol/protocol.rs +++ b/rosenpass/src/protocol/protocol.rs @@ -3,184 +3,58 @@ //! It is merged entirely into [crate::protocol] and should be split up into multiple //! files. -use std::borrow::Borrow; -use std::convert::Infallible; -use std::fmt::Debug; -use std::mem::size_of; -use std::ops::Deref; +use std::collections::hash_map::{ + Entry::{Occupied, Vacant}, + HashMap, +}; use std::{ - collections::hash_map::{ - Entry::{Occupied, Vacant}, - HashMap, - }, - fmt::Display, + borrow::Borrow, + fmt::{Debug, Display}, + mem::size_of, + ops::Deref, }; use anyhow::{bail, ensure, Context, Result}; -use rand::Fill as Randomize; - use memoffset::span_of; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::hash_domain::{SecretHashDomain, SecretHashDomainNamespace}; -use rosenpass_ciphers::kem::{EphemeralKem, StaticKem}; -use rosenpass_ciphers::keyed_hash; -use rosenpass_ciphers::{aead, xaead, KEY_LEN}; -use rosenpass_constant_time as constant_time; -use rosenpass_secret_memory::{Public, PublicBox, Secret}; -use rosenpass_to::ops::copy_slice; -use rosenpass_to::To; -use rosenpass_util::functional::ApplyExt; -use rosenpass_util::mem::DiscardResultExt; -use rosenpass_util::{cat, mem::cpy_min, time::Timebase}; use zerocopy::{AsBytes, FromBytes, Ref}; +use rosenpass_cipher_traits::primitives::{ + Aead as _, AeadWithNonceInCiphertext, Kem, KeyedHashInstance, +}; +use rosenpass_ciphers::hash_domain::{SecretHashDomain, SecretHashDomainNamespace}; +use rosenpass_ciphers::{Aead, EphemeralKem, KeyedHash, StaticKem, XAead}; +use rosenpass_constant_time as constant_time; +use rosenpass_secret_memory::{Public, Secret}; +use rosenpass_to::{ops::copy_slice, To}; +use rosenpass_util::{ + cat, + functional::ApplyExt, + mem::{cpy_min, DiscardResultExt}, + time::Timebase, +}; + use crate::{hash_domains, msgs::*, RosenpassError}; -// CONSTANTS & SETTINGS ////////////////////////// +use super::basic_types::{ + BiscuitId, EPk, ESk, MsgBuf, PeerId, PeerNo, PublicSymKey, SPk, SSk, SessionId, SymKey, + XAEADNonce, +}; +use super::constants::{ + BISCUIT_EPOCH, COOKIE_SECRET_EPOCH, COOKIE_SECRET_LEN, COOKIE_VALUE_LEN, + PEER_COOKIE_VALUE_EPOCH, REJECT_AFTER_TIME, REKEY_AFTER_TIME_INITIATOR, + REKEY_AFTER_TIME_RESPONDER, RETRANSMIT_DELAY_BEGIN, RETRANSMIT_DELAY_END, + RETRANSMIT_DELAY_GROWTH, RETRANSMIT_DELAY_JITTER, +}; +use super::cookies::{BiscuitKey, CookieSecret, CookieStore}; +use super::index::{PeerIndex, PeerIndexKey}; +use super::osk_domain_separator::OskDomainSeparator; +use super::timing::{has_happened, Timing, BCE, UNENDING}; +use super::zerocopy::{truncating_cast_into, truncating_cast_into_nomut}; -/// A type for time, e.g. for backoff before re-tries -pub type Timing = f64; - -/// Magic time stamp to indicate some object is ancient; "Before Common Era" -/// -/// This is for instance used as a magic time stamp indicating age when some -/// cryptographic object certainly needs to be refreshed. -/// -/// Using this instead of Timing::MIN or Timing::INFINITY to avoid floating -/// point math weirdness. -pub const BCE: Timing = -3600.0 * 24.0 * 356.0 * 10_000.0; - -/// Magic time stamp to indicate that some process is not time-limited -/// -/// Actually it's eight hours; This is intentional to avoid weirdness -/// regarding unexpectedly large numbers in system APIs as this is < i16::MAX -pub const UNENDING: Timing = 3600.0 * 8.0; - -/// Time after which the responder attempts to rekey the session -/// -/// From the wireguard paper: rekey every two minutes, -/// discard the key if no rekey is achieved within three -pub const REKEY_AFTER_TIME_RESPONDER: Timing = 120.0; -/// Time after which the initiator attempts to rekey the session. -/// -/// This happens ten seconds after [REKEY_AFTER_TIME_RESPONDER], so -/// parties would usually switch roles after every handshake. -/// -/// From the wireguard paper: rekey every two minutes, -/// discard the key if no rekey is achieved within three -pub const REKEY_AFTER_TIME_INITIATOR: Timing = 130.0; -/// Time after which either party rejects the current key. -/// -/// At this point a new key should have been negotiated. -/// Rejection happens 50-60 seconds after key renegotiation -/// to allow for a graceful handover. -/// -/// From the wireguard paper: rekey every two minutes, -/// discard the key if no rekey is achieved within three -pub const REJECT_AFTER_TIME: Timing = 180.0; - -/// Maximum period between sending rekey initiation messages -/// -/// From the wireguard paper; "under no circumstances send an initiation message more than once every 5 seconds" -pub const REKEY_TIMEOUT: Timing = 5.0; - -/// The length of the `cookie_secret` in the [whitepaper](https://rosenpass.eu/whitepaper.pdf) -pub const COOKIE_SECRET_LEN: usize = MAC_SIZE; -/// The life time of the `cookie_secret` in the [whitepaper](https://rosenpass.eu/whitepaper.pdf) -pub const COOKIE_SECRET_EPOCH: Timing = 120.0; - -/// Length of a cookie value (see info about the cookie mechanism in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)) -pub const COOKIE_VALUE_LEN: usize = MAC_SIZE; -/// Time after which to delete a cookie, as the initiator, for a certain peer (see info about the cookie mechanism in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)) -pub const PEER_COOKIE_VALUE_EPOCH: Timing = 120.0; - -/// Seconds until the biscuit key is changed; we issue biscuits -/// using one biscuit key for one epoch and store the biscuit for -/// decryption for a second epoch -/// -/// The biscuit mechanism is used to make sure the responder is stateless in our protocol. -pub const BISCUIT_EPOCH: Timing = 300.0; - -/// The initiator opportunistically retransmits their messages; it applies an increasing delay -/// between each retreansmission. This is the factor by which the delay grows after each -/// retransmission. -pub const RETRANSMIT_DELAY_GROWTH: Timing = 2.0; -/// The initiator opportunistically retransmits their messages; it applies an increasing delay -/// between each retreansmission. This is the initial delay between retransmissions. -pub const RETRANSMIT_DELAY_BEGIN: Timing = 0.5; -/// The initiator opportunistically retransmits their messages; it applies an increasing delay -/// between each retreansmission. This is the maximum delay between retransmissions. -pub const RETRANSMIT_DELAY_END: Timing = 10.0; -/// The initiator opportunistically retransmits their messages; it applies an increasing delay -/// between each retreansmission. This is the jitter (randomness) applied to the retransmission -/// delay. -pub const RETRANSMIT_DELAY_JITTER: Timing = 0.5; - -/// This is the maximum delay that can separate two events for us to consider the events to have -/// happened at the same time. -pub const EVENT_GRACE: Timing = 0.0025; - -// UTILITY FUNCTIONS ///////////////////////////// - -/// An even `ev` has happened relative to a point in time `now` -/// if the `ev` does not lie in the future relative to now. -/// -/// An event lies in the future relative to `now` if -/// does not lie in the past or present. -/// -/// An event `ev` lies in the past if `ev < now`. It lies in the -/// present if the absolute difference between `ev` and `now` is -/// smaller than [EVENT_GRACE]. -/// -/// Think of this as `ev <= now` for with [EVENT_GRACE] applied. -/// -/// # Examples -/// -/// ``` -/// use rosenpass::protocol::{has_happened, EVENT_GRACE}; -/// assert!(has_happened(EVENT_GRACE * -1.0, 0.0)); -/// assert!(has_happened(0.0, 0.0)); -/// assert!(has_happened(EVENT_GRACE * 0.999, 0.0)); -/// assert!(!has_happened(EVENT_GRACE * 1.001, 0.0)); -/// ``` -pub fn has_happened(ev: Timing, now: Timing) -> bool { - (ev - now) < EVENT_GRACE -} +#[cfg(feature = "trace_bench")] +use rosenpass_util::trace_bench::Trace as _; // DATA STRUCTURES & BASIC TRAITS & ACCESSORS //// - -/// Static public key -/// -/// Using [PublicBox] instead of [Public] because Classic McEliece keys are very large. -pub type SPk = PublicBox<{ StaticKem::PK_LEN }>; -/// Static secret key -pub type SSk = Secret<{ StaticKem::SK_LEN }>; -/// Ephemeral public key -pub type EPk = Public<{ EphemeralKem::PK_LEN }>; -/// Ephemeral secret key -pub type ESk = Secret<{ EphemeralKem::SK_LEN }>; - -/// Symmetric key -pub type SymKey = Secret; -/// Symmetric hash -pub type SymHash = Public; - -/// Peer ID (derived from the public key, see the hash derivations in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)) -pub type PeerId = Public; -/// Session ID -pub type SessionId = Public; -/// Biscuit ID -pub type BiscuitId = Public; - -/// Nonce for use with random-nonce AEAD -pub type XAEADNonce = Public<{ xaead::NONCE_LEN }>; - -/// Buffer capably of holding any Rosenpass protocol message -pub type MsgBuf = Public; - -/// Server-local peer number; this is just the index in [CryptoServer::peers] -pub type PeerNo = usize; - /// This is the implementation of our cryptographic protocol. /// /// The scope of this is: @@ -230,12 +104,12 @@ pub struct CryptoServer { /// List of peers and their session and handshake states pub peers: Vec, - /// Index into the list of peers. See [IndexKey] for details. - pub index: HashMap, + /// Index into the list of peers. See [PeerIndexKey] for details. + pub index: PeerIndex, /// Hash key for known responder confirmation responses. /// /// These hashes are then used for lookups in [Self::index] using - /// the [IndexKey::KnownInitConfResponse] enum case. + /// the [PeerIndexKey::KnownInitConfResponse] enum case. /// /// This is used to allow for retransmission of responder confirmation (i.e. /// [Envelope]<[EmptyData]>) messages in response to [Envelope]<[InitConf]> @@ -264,104 +138,30 @@ pub struct CryptoServer { pub cookie_secrets: [CookieSecret; 2], } -/// Container for storing cookie secrets like [BiscuitKey] or [CookieSecret]. -/// -/// This is really just a secret key and a time stamp of creation. Concrete -/// usages (such as for the biscuit key) impose a time limit about how long -/// a key can be used and the time of creation is used to impose that time limit. -/// -/// # Examples -/// -/// ``` -/// use rosenpass_util::time::Timebase; -/// use rosenpass::protocol::{BCE, SymKey, CookieStore}; -/// -/// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); -/// -/// let fixed_secret = SymKey::random(); -/// let timebase = Timebase::default(); -/// -/// let mut store = CookieStore::<32>::new(); -/// assert_ne!(store.value.secret(), SymKey::zero().secret()); -/// assert_eq!(store.created_at, BCE); -/// -/// let time_before_call = timebase.now(); -/// store.update(&timebase, fixed_secret.secret()); -/// assert_eq!(store.value.secret(), fixed_secret.secret()); -/// assert!(store.created_at < timebase.now()); -/// assert!(store.created_at > time_before_call); -/// -/// // Same as new() -/// store.erase(); -/// assert_ne!(store.value.secret(), SymKey::zero().secret()); -/// assert_eq!(store.created_at, BCE); -/// -/// let secret_before_call = store.value.clone(); -/// let time_before_call = timebase.now(); -/// store.randomize(&timebase); -/// assert_ne!(store.value.secret(), secret_before_call.secret()); -/// assert!(store.created_at < timebase.now()); -/// assert!(store.created_at > time_before_call); -/// ``` -#[derive(Debug)] -pub struct CookieStore { - /// Time of creation of the secret key - pub created_at: Timing, - /// The secret key - pub value: Secret, +/// Specifies the protocol version used by a peer. +#[derive(Debug, Clone)] +pub enum ProtocolVersion { + V02, + V03, } -/// Stores cookie secret, which is used to create a rotating the cookie value -/// -/// Concrete value is in [CryptoServer::cookie_secrets]. -/// -/// The pointer type is [ServerCookieSecretPtr]. -pub type CookieSecret = CookieStore; +impl ProtocolVersion { + /// Returns the [KeyedHash] used by a protocol version. + pub fn keyed_hash(&self) -> KeyedHash { + match self { + ProtocolVersion::V02 => KeyedHash::incorrect_hmac_blake2b(), + ProtocolVersion::V03 => KeyedHash::keyed_shake256(), + } + } +} -/// Storage for our biscuit keys. -/// -/// The biscuit keys encrypt what we call "biscuits". -/// These biscuits contain the responder state for a particular handshake. By moving -/// state into these biscuits, we make sure the responder is stateless. -/// -/// A Biscuit is like a fancy cookie. To avoid state disruption attacks, -/// the responder doesn't store state. Instead the state is stored in a -/// Biscuit, that is encrypted using the [BiscuitKey] which is only known to -/// the Responder. Thus secrecy of the Responder state is not violated, still -/// the responder can avoid storing this state. -/// -/// Concrete value is in [CryptoServer::biscuit_keys]. -/// -/// The pointer type is [BiscuitKeyPtr]. -pub type BiscuitKey = CookieStore; - -/// We maintain various indices in [CryptoServer::index], mapping some key to a particular -/// [PeerNo], i.e. to an index in [CryptoServer::peers]. These are the possible index key. -#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub enum IndexKey { - /// Lookup of a particular peer given the [PeerId], i.e. a value derived from the peers public - /// key as created by [CryptoServer::pidm] or [Peer::pidt]. - /// - /// The peer id is used by the initiator to tell the responder about its identity in - /// [crate::msgs::InitHello]. - /// - /// See also the pointer types [PeerPtr]. - Peer(PeerId), - /// Lookup of a particular session id. - /// - /// This is used to look up both established sessions (see - /// [CryptoServer::lookup_session]) and ongoing handshakes (see [CryptoServer::lookup_handshake]). - /// - /// Lookup of a peer to get an established session or a handshake is sufficient, because a peer - /// contains a limited number of sessions and handshakes ([Peer::session] and [Peer::handshake] respectively). - /// - /// See also the pointer types [IniHsPtr] and [SessionPtr]. - Sid(SessionId), - /// Lookup of a cached response ([Envelope]<[EmptyData]>) to an [InitConf] (i.e. - /// [Envelope]<[InitConf]>) message. - /// - /// See [KnownInitConfResponsePtr] on how this value is maintained. - KnownInitConfResponse(KnownResponseHash), +impl From for ProtocolVersion { + fn from(v: crate::config::ProtocolVersion) -> Self { + match v { + crate::config::ProtocolVersion::V02 => ProtocolVersion::V02, + crate::config::ProtocolVersion::V03 => ProtocolVersion::V03, + } + } } /// A peer that the server can execute a key exchange with. @@ -369,34 +169,38 @@ pub enum IndexKey { /// Peers generally live in [CryptoServer::peers]. [PeerNo] captures an array /// into this field and [PeerPtr] is a wrapper around a [PeerNo] imbued with /// peer specific functionality. [CryptoServer::index] contains a list of lookup-keys -/// for retrieving peers using various keys (see [IndexKey]). +/// for retrieving peers using various keys (see [PeerIndexKey]). /// /// # Examples /// /// ``` /// use std::ops::DerefMut; -/// use rosenpass::protocol::{SSk, SPk, SymKey, Peer}; -/// use rosenpass_ciphers::kem::StaticKem; -/// use rosenpass_cipher_traits::Kem; +/// +/// use rosenpass_ciphers::StaticKem; +/// use rosenpass_cipher_traits::primitives::Kem; +/// +/// use rosenpass::protocol::basic_types::{SSk, SPk, SymKey}; +/// use rosenpass::protocol::{Peer, ProtocolVersion}; +/// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; /// /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); /// /// let (mut sskt, mut spkt) = (SSk::zero(), SPk::zero()); -/// StaticKem::keygen(sskt.secret_mut(), spkt.deref_mut())?; +/// StaticKem.keygen(sskt.secret_mut(), spkt.deref_mut())?; /// /// let (mut sskt2, mut spkt2) = (SSk::zero(), SPk::zero()); -/// StaticKem::keygen(sskt2.secret_mut(), spkt2.deref_mut())?; +/// StaticKem.keygen(sskt2.secret_mut(), spkt2.deref_mut())?; /// /// let psk = SymKey::random(); /// /// // Creation with a PSK -/// let peer_psk = Peer::new(psk, spkt.clone()); +/// let peer_psk = Peer::new(psk, spkt.clone(), ProtocolVersion::V03, OskDomainSeparator::default()); /// /// // Creation without a PSK -/// let peer_nopsk = Peer::new(SymKey::zero(), spkt); +/// let peer_nopsk = Peer::new(SymKey::zero(), spkt, ProtocolVersion::V03, OskDomainSeparator::default()); /// /// // Create a second peer -/// let peer_psk_2 = Peer::new(SymKey::zero(), spkt2); +/// let peer_psk_2 = Peer::new(SymKey::zero(), spkt2, ProtocolVersion::V03, OskDomainSeparator::default()); /// /// // Peer ID does not depend on PSK, but it does depend on the public key /// assert_eq!(peer_psk.pidt()?, peer_nopsk.pidt()?); @@ -426,7 +230,7 @@ pub struct Peer { pub biscuit_used: BiscuitId, /// The last established session /// - /// This is indexed though [IndexKey::Sid]. + /// This is indexed though [PeerIndexKey::Sid]. pub session: Option, /// Ongoing handshake, in initiator mode. /// @@ -434,7 +238,7 @@ pub struct Peer { /// because the state is stored inside a [Biscuit] to make sure the responder /// is stateless. /// - /// This is indexed though [IndexKey::Sid]. + /// This is indexed though [PeerIndexKey::Sid]. pub handshake: Option, /// Used to make sure that the same [PollResult::SendInitiation] event is never issued twice. /// @@ -446,12 +250,16 @@ pub struct Peer { /// [Envelope]<[EmptyData]>. /// /// Upon reception of an InitConf message, [CryptoServer::handle_msg] first checks - /// if a cached response exists through [IndexKey::KnownInitConfResponse]. If one exists, + /// if a cached response exists through [PeerIndexKey::KnownInitConfResponse]. If one exists, /// then this field must be set to [Option::Some] and the cached response is returned. /// /// This allows us to perform retransmission for the purpose of dealing with packet loss /// on the network without having to account for it in the cryptographic code itself. pub known_init_conf_response: Option, + /// The protocol version used by with this peer. + pub protocol_version: ProtocolVersion, + /// Domain separator for generated OSKs + pub osk_domain_separator: OskDomainSeparator, } impl Peer { @@ -460,14 +268,15 @@ impl Peer { /// This is dirty but allows us to perform easy incremental construction of [Self]. /// /// ``` - /// use rosenpass::protocol::{Peer, SymKey, SPk}; + /// use rosenpass::protocol::basic_types::{SymKey, SPk}; + /// use rosenpass::protocol::{Peer, ProtocolVersion}; /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - /// let p = Peer::zero(); + /// let p = Peer::zero(ProtocolVersion::V03); /// assert_eq!(p.psk.secret(), SymKey::zero().secret()); /// assert_eq!(p.spkt, SPk::zero()); /// // etc. /// ``` - pub fn zero() -> Self { + pub fn zero(protocol_version: ProtocolVersion) -> Self { Self { psk: SymKey::zero(), spkt: SPk::zero(), @@ -476,6 +285,8 @@ impl Peer { initiation_requested: false, handshake: None, known_init_conf_response: None, + protocol_version, + osk_domain_separator: OskDomainSeparator::default(), } } } @@ -578,6 +389,8 @@ pub struct InitiatorHandshake { /// mechanism. /// /// TODO: cookie_value should be an Option<_> + /// TODO: This should not use CookieStore, which exists to store randomly generated cookie + /// secrets /// /// This value seems to default-initialized with a random value according to /// [Self::zero_with_timestamp], which does not really make sense since this @@ -625,7 +438,7 @@ fn known_response_format() { response: Envelope::new_zeroed(), }; let s = format!("{v:?}"); - assert!(s.contains("response")); // Smoke test only, its a formatter + assert!(s.contains("response")); // Smoke test only, it's a formatter } /// Known [EmptyData] response to an [InitConf] message @@ -634,14 +447,14 @@ fn known_response_format() { pub type KnownInitConfResponse = KnownResponse; /// The type used to represent the hash of a known response -/// in the context of [KnownResponse]/[IndexKey::KnownInitConfResponse] +/// in the context of [KnownResponse]/[PeerIndexKey::KnownInitConfResponse] pub type KnownResponseHash = Public<16>; /// Object that produces [KnownResponseHash]. /// /// Merely a key plus some utility functions. /// -/// See [IndexKey::KnownInitConfResponse] and [KnownResponse::request_mac] +/// See [PeerIndexKey::KnownInitConfResponse] and [KnownResponse::request_mac] /// /// # Examples /// @@ -692,8 +505,11 @@ impl KnownResponseHasher { /// Panics in case of a problem with this underlying hash function pub fn hash(&self, msg: &Envelope) -> KnownResponseHash { let data = &msg.as_bytes()[span_of!(Envelope, msg_type..cookie)]; - let hash = keyed_hash::hash(self.key.secret(), data) - .to_this(Public::<32>::zero) + // This function is only used internally and results are not propagated + // to outside the peer. Thus, it uses SHAKE256 exclusively. + let mut hash = [0u8; 32]; + KeyedHash::keyed_shake256() + .keyed_hash(self.key.secret(), data, &mut hash) .unwrap(); Public::from_slice(&hash[0..16]) // truncate to 16 bytes } @@ -754,7 +570,7 @@ pub enum Lifecycle { /// /// If a secret, it must be zeroized and disposed. Dead, - /// Soon to be dead. Do not use any more. + /// Soon to be dead. Do not use anymore. /// /// If a secret, it might be used for decoding (decrypting) /// data, but must not be used for encryption of cryptographic values. @@ -803,12 +619,13 @@ pub trait Mortal { /// /// ``` /// use std::ops::DerefMut; -/// use rosenpass_ciphers::kem::StaticKem; -/// use rosenpass::protocol::{SSk, SPk, testutils::ServerForTesting}; +/// use rosenpass_ciphers::StaticKem; +/// use rosenpass::protocol::basic_types::{SSk, SPk}; +/// use rosenpass::protocol::{testutils::ServerForTesting, ProtocolVersion}; /// /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); /// -/// let (peer, (_, spkt), mut srv) = ServerForTesting::new()?.tuple(); +/// let (peer, (_, spkt), mut srv) = ServerForTesting::new(ProtocolVersion::V03)?.tuple(); /// /// // Immutable access /// assert_eq!(peer.get(&srv).spkt, spkt); @@ -1209,7 +1026,7 @@ impl KnownInitConfResponsePtr { pub fn remove(&self, srv: &mut CryptoServer) -> Option { let peer = self.peer(); let val = peer.get_mut(srv).known_init_conf_response.take()?; - let lookup_key = IndexKey::KnownInitConfResponse(val.request_mac); + let lookup_key = PeerIndexKey::KnownInitConfResponse(val.request_mac); srv.index.remove(&lookup_key).unwrap(); Some(val) } @@ -1228,7 +1045,7 @@ impl KnownInitConfResponsePtr { pub fn insert(&self, srv: &mut CryptoServer, known_response: KnownInitConfResponse) { self.remove(srv).discard_result(); - let index_key = IndexKey::KnownInitConfResponse(known_response.request_mac); + let index_key = PeerIndexKey::KnownInitConfResponse(known_response.request_mac); self.peer().get_mut(srv).known_init_conf_response = Some(known_response); // There is a question here whether we should just discard the result…or panic if the @@ -1329,9 +1146,9 @@ impl KnownInitConfResponsePtr { /// Calculate an appropriate index key for `req` /// - /// Merely forwards [Self::index_key_for_msg] and wraps the result in [IndexKey::KnownInitConfResponse] - pub fn index_key_for_msg(srv: &CryptoServer, req: &Envelope) -> IndexKey { - Self::index_key_hash_for_msg(srv, req).apply(IndexKey::KnownInitConfResponse) + /// Merely forwards [Self::index_key_for_msg] and wraps the result in [PeerIndexKey::KnownInitConfResponse] + pub fn index_key_for_msg(srv: &CryptoServer, req: &Envelope) -> PeerIndexKey { + Self::index_key_hash_for_msg(srv, req).apply(PeerIndexKey::KnownInitConfResponse) } } @@ -1344,14 +1161,15 @@ impl CryptoServer { /// /// ``` /// use std::ops::DerefMut; - /// use rosenpass::protocol::{SSk, SPk, CryptoServer}; - /// use rosenpass_ciphers::kem::StaticKem; - /// use rosenpass_cipher_traits::Kem; + /// use rosenpass::protocol::basic_types::{SSk, SPk}; + /// use rosenpass::protocol::{CryptoServer, ProtocolVersion}; + /// use rosenpass_ciphers::StaticKem; + /// use rosenpass_cipher_traits::primitives::Kem; /// /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); /// /// let (mut sskm, mut spkm) = (SSk::zero(), SPk::zero()); - /// StaticKem::keygen(sskm.secret_mut(), spkm.deref_mut())?; + /// StaticKem.keygen(sskm.secret_mut(), spkm.deref_mut())?; /// /// let srv = CryptoServer::new(sskm, spkm.clone()); /// assert_eq!(srv.spkm, spkm); @@ -1388,9 +1206,9 @@ impl CryptoServer { /// Calculate the peer ID of this CryptoServer #[rustfmt::skip] - pub fn pidm(&self) -> Result { + pub fn pidm(&self, keyed_hash: KeyedHash) -> Result { Ok(Public::new( - hash_domains::peerid()? + hash_domains::peerid(keyed_hash)? .mix(self.spkm.deref())? .into_value())) } @@ -1403,32 +1221,41 @@ impl CryptoServer { (0..l).map(move |i| PeerPtr((i + n) % l)) } - /// Add a peer with an optional pre shared key (`psk`) and its public key (`pk`) + /// Add a peer with an optional pre shared key (`psk`), its public key (`pk`) and the peer's + /// protocol version (`protocol_version`). /// /// ``` /// use std::ops::DerefMut; - /// use rosenpass::protocol::{SSk, SPk, SymKey, CryptoServer}; - /// use rosenpass_ciphers::kem::StaticKem; - /// use rosenpass_cipher_traits::Kem; + /// use rosenpass::protocol::basic_types::{SSk, SPk, SymKey}; + /// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; + /// use rosenpass::protocol::{CryptoServer, ProtocolVersion}; + /// use rosenpass_ciphers::StaticKem; + /// use rosenpass_cipher_traits::primitives::Kem; /// /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); /// /// let (mut sskm, mut spkm) = (SSk::zero(), SPk::zero()); - /// StaticKem::keygen(sskm.secret_mut(), spkm.deref_mut())?; + /// StaticKem.keygen(sskm.secret_mut(), spkm.deref_mut())?; /// let mut srv = CryptoServer::new(sskm, spkm); /// /// let (mut sskt, mut spkt) = (SSk::zero(), SPk::zero()); - /// StaticKem::keygen(sskt.secret_mut(), spkt.deref_mut())?; + /// StaticKem.keygen(sskt.secret_mut(), spkt.deref_mut())?; /// /// let psk = SymKey::random(); - /// - /// let peer = srv.add_peer(Some(psk), spkt.clone())?; + /// // We use the latest protocol version for the example. + /// let peer = srv.add_peer(Some(psk), spkt.clone(), ProtocolVersion::V03, OskDomainSeparator::for_wireguard_psk())?; /// /// assert_eq!(peer.get(&srv).spkt, spkt); /// /// Ok::<(), anyhow::Error>(()) /// ``` - pub fn add_peer(&mut self, psk: Option, pk: SPk) -> Result { + pub fn add_peer( + &mut self, + psk: Option, + pk: SPk, + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, + ) -> Result { let peer = Peer { psk: psk.unwrap_or_else(SymKey::zero), spkt: pk, @@ -1437,10 +1264,12 @@ impl CryptoServer { handshake: None, known_init_conf_response: None, initiation_requested: false, + protocol_version, + osk_domain_separator, }; let peerid = peer.pidt()?; let peerno = self.peers.len(); - match self.index.entry(IndexKey::Peer(peerid)) { + match self.index.entry(PeerIndexKey::Peer(peerid)) { Occupied(_) => bail!( "Cannot insert peer with id {:?}; peer with this id already registered.", peerid @@ -1464,7 +1293,7 @@ impl CryptoServer { /// To rgister a session, you should generally use [SessionPtr::insert] or [IniHsPtr::insert] /// instead of this, more lower level function. pub fn register_session(&mut self, id: SessionId, peer: PeerPtr) -> Result<()> { - match self.index.entry(IndexKey::Sid(id)) { + match self.index.entry(PeerIndexKey::Sid(id)) { Occupied(p) if PeerPtr(*p.get()) == peer => {} // Already registered Occupied(_) => bail!("Cannot insert session with id {:?}; id is in use.", id), Vacant(e) => { @@ -1483,7 +1312,7 @@ impl CryptoServer { /// To unregister a session, you should generally use [SessionPtr::take] or [IniHsPtr::take] /// instead of this, more lower level function. pub fn unregister_session(&mut self, id: SessionId) { - self.index.remove(&IndexKey::Sid(id)); + self.index.remove(&PeerIndexKey::Sid(id)); } /// Unregister a session previously registered using [Self::register_session], @@ -1512,7 +1341,9 @@ impl CryptoServer { /// This function is used in cryptographic message processing /// [CryptoServer::handle_init_hello], and [HandshakeState::load_biscuit] pub fn find_peer(&self, id: PeerId) -> Option { - self.index.get(&IndexKey::Peer(id)).map(|no| PeerPtr(*no)) + self.index + .get(&PeerIndexKey::Peer(id)) + .map(|no| PeerPtr(*no)) } /// Look up a handshake given its session id [HandshakeState::sidi] @@ -1520,7 +1351,7 @@ impl CryptoServer { /// This is called `lookup_session` in [whitepaper](https://rosenpass.eu/whitepaper.pdf). pub fn lookup_handshake(&self, id: SessionId) -> Option { self.index - .get(&IndexKey::Sid(id)) // lookup the session in the index + .get(&PeerIndexKey::Sid(id)) // lookup the session in the index .map(|no| IniHsPtr(*no)) // convert to peer pointer .filter(|hsptr| { hsptr @@ -1536,7 +1367,7 @@ impl CryptoServer { /// This is called `lookup_session` in [whitepaper](https://rosenpass.eu/whitepaper.pdf). pub fn lookup_session(&self, id: SessionId) -> Option { self.index - .get(&IndexKey::Sid(id)) + .get(&PeerIndexKey::Sid(id)) .map(|no| SessionPtr(*no)) .filter(|sptr| { sptr.get(self) @@ -1549,7 +1380,7 @@ impl CryptoServer { /// Retrieve the active biscuit key, cycling biscuit keys if necessary. /// /// Two biscuit keys are maintained inside [Self::biscuit_keys]; they are - /// considered fresh ([Lifecycle::Young]) for one [BISCUIT_EPOCH] after creation + /// considered fresh ([Lifecycle::Young]) for one [BISCUIT_EPOCH] after creation, /// and they are considered stale ([Lifecycle::Retired]) for another [BISCUIT_EPOCH]. /// /// While young, they are used for encryption of biscuits and while retired they are @@ -1624,7 +1455,12 @@ impl Peer { /// # Examples /// /// See example in [Self]. - pub fn new(psk: SymKey, pk: SPk) -> Peer { + pub fn new( + psk: SymKey, + pk: SPk, + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, + ) -> Peer { Peer { psk, spkt: pk, @@ -1633,11 +1469,13 @@ impl Peer { handshake: None, known_init_conf_response: None, initiation_requested: false, + protocol_version, + osk_domain_separator, } } /// Compute the peer ID of the peer, - /// as specified in the the [whitepaper](https://rosenpass.eu/whitepaper.pdf). + /// as specified in the [whitepaper](https://rosenpass.eu/whitepaper.pdf). /// /// # Examples /// @@ -1645,7 +1483,7 @@ impl Peer { #[rustfmt::skip] pub fn pidt(&self) -> Result { Ok(Public::new( - hash_domains::peerid()? + hash_domains::peerid(self.protocol_version.keyed_hash())? .mix(self.spkt.deref())? .into_value())) } @@ -1658,20 +1496,21 @@ impl Session { /// /// ``` /// use rosenpass::protocol::{Session, HandshakeRole}; + /// use rosenpass_ciphers::KeyedHash; /// /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); /// - /// let s = Session::zero(); + /// let s = Session::zero(KeyedHash::keyed_shake256()); /// assert_eq!(s.created_at, 0.0); /// assert_eq!(s.handshake_role, HandshakeRole::Initiator); /// ``` - pub fn zero() -> Self { + pub fn zero(keyed_hash: KeyedHash) -> Self { Self { created_at: 0.0, sidm: SessionId::zero(), sidt: SessionId::zero(), handshake_role: HandshakeRole::Initiator, - ck: SecretHashDomain::zero().dup(), + ck: SecretHashDomain::zero(keyed_hash).dup(), txkm: SymKey::zero(), txkt: SymKey::zero(), txnm: 0, @@ -1886,7 +1725,7 @@ impl Mortal for KnownInitConfResponsePtr { /// # Examples /// /// ``` -/// use rosenpass::protocol::{Timing, Mortal, MortalExt, Lifecycle, CryptoServer}; +/// use rosenpass::protocol::{timing::Timing, Mortal, MortalExt, Lifecycle, CryptoServer, ProtocolVersion}; /// use rosenpass::protocol::testutils::{ServerForTesting, time_travel_forward}; /// /// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); @@ -1896,7 +1735,7 @@ impl Mortal for KnownInitConfResponsePtr { /// const D : Timing = 24.0 * H; /// const Y : Timing = 356.0 * D; /// -/// let mut ts = ServerForTesting::new()?; +/// let mut ts = ServerForTesting::new(ProtocolVersion::V03)?; /// /// fn eq_up_to_minute(a: Timing, b: Timing) -> bool { /// (a - b) < M @@ -2080,7 +1919,7 @@ impl CryptoServer { /// Keeps track of messages processed, and qualifies messages using /// cookie based DoS mitigation. /// - /// If recieving a InitHello message, it dispatches message for further processing + /// If receiving a InitHello message, it dispatches message for further processing /// to `process_msg` handler if cookie is valid otherwise sends a cookie reply /// message for sender to process and verify for messages part of the handshake phase /// @@ -2098,6 +1937,18 @@ impl CryptoServer { /// /// - test::cookie_reply_mechanism_responder_under_load /// - test::cookie_reply_mechanism_initiator_bails_on_message_under_load + #[cfg(not(feature = "experiment_cookie_dos_mitigation"))] + #[inline] + pub fn handle_msg_under_load( + &mut self, + rx_buf: &[u8], + tx_buf: &mut [u8], + host_identification: &H, + ) -> Result { + self.handle_msg(rx_buf, tx_buf) + } + + #[cfg(feature = "experiment_cookie_dos_mitigation")] pub fn handle_msg_under_load( &mut self, rx_buf: &[u8], @@ -2109,7 +1960,6 @@ impl CryptoServer { let mut rx_mac = [0u8; MAC_SIZE]; let mut rx_sid = [0u8; 4]; let msg_type: Result = rx_buf[0].try_into(); - // TODO: Th match msg_type { Ok(MsgType::InitConf) => { log::debug!( @@ -2136,13 +1986,13 @@ impl CryptoServer { let cookie_secret = cookie_secret.get(self).value.secret(); let mut cookie_value = [0u8; 16]; cookie_value.copy_from_slice( - &hash_domains::cookie_value()? + &hash_domains::cookie_value(KeyedHash::keyed_shake256())? .mix(cookie_secret)? .mix(host_identification.encode())? .into_value()[..16], ); - //Most recently filled value is active cookie value + // Most recently filled value is active cookie value if active_cookie_value.is_none() { active_cookie_value = Some(cookie_value); } @@ -2152,7 +2002,7 @@ impl CryptoServer { let msg_in = Ref::<&[u8], Envelope>::new(rx_buf) .ok_or(RosenpassError::BufferSizeMismatch)?; expected.copy_from_slice( - &hash_domains::cookie()? + &hash_domains::cookie(KeyedHash::keyed_shake256())? .mix(&cookie_value)? .mix(&msg_in.as_bytes()[span_of!(Envelope, msg_type..cookie)])? .into_value()[..16], @@ -2177,7 +2027,7 @@ impl CryptoServer { } } - //Otherwise send cookie reply + // Otherwise send cookie reply if active_cookie_value.is_none() { bail!("No active cookie value found"); } @@ -2189,7 +2039,7 @@ impl CryptoServer { ); let cookie_value = active_cookie_value.unwrap(); - let cookie_key = hash_domains::cookie_key()? + let cookie_key = hash_domains::cookie_key(KeyedHash::keyed_shake256())? .mix(self.spkm.deref())? .into_value(); @@ -2200,7 +2050,7 @@ impl CryptoServer { msg_out.inner.msg_type = MsgType::CookieReply.into(); msg_out.inner.sid = rx_sid; - xaead::encrypt( + XAead.encrypt_with_nonce_in_ctxt( &mut msg_out.inner.cookie_encrypted[..], &cookie_key, &nonce.value, @@ -2208,10 +2058,13 @@ impl CryptoServer { &cookie_value, )?; - msg_out - .padding - .try_fill(&mut rosenpass_secret_memory::rand::rng()) - .unwrap(); + { + use rand::Fill; + msg_out + .padding + .try_fill(&mut rosenpass_secret_memory::rand::rng()) + .unwrap(); + } // length of the response let _len = Some(size_of::()); @@ -2269,24 +2122,54 @@ impl CryptoServer { log::debug!("Rx {:?}, processing", msg_type); + let mut msg_out = truncating_cast_into::>(tx_buf)?; + let peer = match msg_type { Ok(MsgType::InitHello) => { let msg_in: Ref<&[u8], Envelope> = Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; - ensure!(msg_in.check_seal(self)?, seal_broken); - let mut msg_out = truncating_cast_into::>(tx_buf)?; - let peer = self.handle_init_hello(&msg_in.payload, &mut msg_out.payload)?; + // At this point, we do not know the hash functon used by the peer, thus we try both, + // with a preference for SHAKE256. + let peer_shake256 = self.handle_init_hello( + &msg_in.payload, + &mut msg_out.payload, + KeyedHash::keyed_shake256(), + ); + let (peer, peer_hash_choice) = match peer_shake256 { + Ok(peer) => (peer, KeyedHash::keyed_shake256()), + Err(_) => { + let peer_blake2b = self.handle_init_hello( + &msg_in.payload, + &mut msg_out.payload, + KeyedHash::incorrect_hmac_blake2b(), + ); + match peer_blake2b { + Ok(peer) => (peer, KeyedHash::incorrect_hmac_blake2b()), + Err(_) => bail!("No valid hash function found for InitHello"), + } + } + }; + // Now, we make sure that the hash function used by the peer is the same as the one + // that is specified in the local configuration. + self.verify_hash_choice_match(peer, peer_hash_choice.clone())?; + + ensure!(msg_in.check_seal(self, peer_hash_choice)?, seal_broken); + len = self.seal_and_commit_msg(peer, MsgType::RespHello, &mut msg_out)?; peer } Ok(MsgType::RespHello) => { let msg_in: Ref<&[u8], Envelope> = Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; - ensure!(msg_in.check_seal(self)?, seal_broken); let mut msg_out = truncating_cast_into::>(tx_buf)?; let peer = self.handle_resp_hello(&msg_in.payload, &mut msg_out.payload)?; + ensure!( + msg_in.check_seal(self, peer.get(self).protocol_version.keyed_hash())?, + seal_broken + ); + len = self.seal_and_commit_msg(peer, MsgType::InitConf, &mut msg_out)?; peer.hs() .store_msg_for_retransmission(self, &msg_out.as_bytes()[..len])?; @@ -2296,7 +2179,6 @@ impl CryptoServer { Ok(MsgType::InitConf) => { let msg_in: Ref<&[u8], Envelope> = Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; - ensure!(msg_in.check_seal(self)?, seal_broken); let mut msg_out = truncating_cast_into::>(tx_buf)?; @@ -2305,6 +2187,11 @@ impl CryptoServer { // Cached response; copy out of cache Some(cached) => { let peer = cached.peer(); + ensure!( + msg_in + .check_seal(self, peer.get(self).protocol_version.keyed_hash())?, + seal_broken + ); let cached = cached .get(self) .map(|v| v.response.borrow()) @@ -2316,7 +2203,31 @@ impl CryptoServer { // No cached response, actually call cryptographic handler None => { - let peer = self.handle_init_conf(&msg_in.payload, &mut msg_out.payload)?; + // At this point, we do not know the hash functon used by the peer, thus we try both, + // with a preference for SHAKE256. + let peer_shake256 = self.handle_init_conf( + &msg_in.payload, + &mut msg_out.payload, + KeyedHash::keyed_shake256(), + ); + let (peer, peer_hash_choice) = match peer_shake256 { + Ok(peer) => (peer, KeyedHash::keyed_shake256()), + Err(_) => { + let peer_blake2b = self.handle_init_conf( + &msg_in.payload, + &mut msg_out.payload, + KeyedHash::incorrect_hmac_blake2b(), + ); + match peer_blake2b { + Ok(peer) => (peer, KeyedHash::incorrect_hmac_blake2b()), + Err(_) => bail!("No valid hash function found for InitHello"), + } + } + }; + // Now, we make sure that the hash function used by the peer is the same as the one + // that is specified in the local configuration. + self.verify_hash_choice_match(peer, peer_hash_choice.clone())?; + ensure!(msg_in.check_seal(self, peer_hash_choice)?, seal_broken); KnownInitConfResponsePtr::insert_for_request_msg( self, @@ -2336,9 +2247,8 @@ impl CryptoServer { Ok(MsgType::EmptyData) => { let msg_in: Ref<&[u8], Envelope> = Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; - ensure!(msg_in.check_seal(self)?, seal_broken); - self.handle_resp_conf(&msg_in.payload)? + self.handle_resp_conf(&msg_in, seal_broken.to_string())? } Ok(MsgType::CookieReply) => { let msg_in: Ref<&[u8], CookieReply> = @@ -2358,6 +2268,21 @@ impl CryptoServer { }) } + /// Given a peer and a [KeyedHash] `peer_hash_choice`, this function checks whether the + /// `peer_hash_choice` matches the hash function that is expected for the peer. + fn verify_hash_choice_match(&self, peer: PeerPtr, peer_hash_choice: KeyedHash) -> Result<()> { + match peer.get(self).protocol_version.keyed_hash() { + KeyedHash::KeyedShake256(_) => match peer_hash_choice { + KeyedHash::KeyedShake256(_) => Ok(()), + KeyedHash::IncorrectHmacBlake2b(_) => bail!("Hash function mismatch"), + }, + KeyedHash::IncorrectHmacBlake2b(_) => match peer_hash_choice { + KeyedHash::KeyedShake256(_) => bail!("Hash function mismatch"), + KeyedHash::IncorrectHmacBlake2b(_) => Ok(()), + }, + } + } + /// This is used to finalize a message in a transmission buffer /// while ensuring that the [Envelope::mac] and [Envelope::cookie] /// fields are properly filled. @@ -2410,7 +2335,7 @@ impl Wait { /// # Examples /// /// ``` - /// use rosenpass::protocol::{Wait, UNENDING}; + /// use rosenpass::protocol::{Wait, timing::UNENDING}; /// /// assert_eq!(Wait::hibernate().0, UNENDING); /// ``` @@ -2424,7 +2349,7 @@ impl Wait { /// # Examples /// /// ``` - /// use rosenpass::protocol::{Wait, UNENDING}; + /// use rosenpass::protocol::{Wait, timing::UNENDING}; /// /// assert_eq!(Wait::immediate_unless(false).0, 0.0); /// assert_eq!(Wait::immediate_unless(true).0, UNENDING); @@ -2442,7 +2367,7 @@ impl Wait { /// # Examples /// /// ``` - /// use rosenpass::protocol::{Wait, UNENDING}; + /// use rosenpass::protocol::{Wait, timing::UNENDING}; /// /// assert_eq!(Wait::or_hibernate(None).0, UNENDING); /// assert_eq!(Wait::or_hibernate(Some(20.0)).0, 20.0); @@ -2459,7 +2384,7 @@ impl Wait { /// # Examples /// /// ``` - /// use rosenpass::protocol::{Wait, UNENDING}; + /// use rosenpass::protocol::{Wait, timing::UNENDING}; /// /// assert_eq!(Wait::or_immediate(None).0, 0.0); /// assert_eq!(Wait::or_immediate(Some(20.0)).0, 20.0); @@ -2476,7 +2401,7 @@ impl Wait { /// # Examples /// /// ``` - /// use rosenpass::protocol::{Wait, UNENDING}; + /// use rosenpass::protocol::{Wait, timing::UNENDING}; /// /// /// assert_eq!(Wait(20.0).and(30.0).0, 30.0); @@ -2523,7 +2448,7 @@ pub enum PollResult { /// The caller should immediately erase any cryptographic keys exchanged with /// the peer previously and then immediately call poll again. /// - /// This is raised after [REKEY_TIMEOUT] if no successful rekey could be achieved. + /// This is raised after [REJECT_AFTER_TIME] if no successful rekey could be achieved. DeleteKey(PeerPtr), /// The caller should invoke [CryptoServer::handle_initiation] and transmit the /// initiation to the other party before invoking poll again. @@ -2548,7 +2473,7 @@ impl PollResult { /// # Examples /// /// ``` - /// use rosenpass::protocol::{PollResult, UNENDING}; + /// use rosenpass::protocol::{PollResult, timing::UNENDING}; /// /// assert!(matches!(PollResult::hibernate(), PollResult::Sleep(UNENDING))); /// ``` @@ -2562,7 +2487,7 @@ impl PollResult { /// # Examples /// /// ``` - /// use rosenpass::protocol::{PollResult, PeerPtr, UNENDING}; + /// use rosenpass::protocol::{PollResult, PeerPtr, timing::UNENDING}; /// /// let p = PeerPtr(0); /// @@ -2817,7 +2742,7 @@ impl PollResult { /// # Examples /// /// ``` -/// use rosenpass::protocol::{begin_poll, PollResult, UNENDING}; +/// use rosenpass::protocol::{begin_poll, PollResult, timing::UNENDING}; /// /// assert!(matches!(begin_poll(), PollResult::Sleep(UNENDING))); /// ``` @@ -3096,7 +3021,7 @@ where { /// Internal business logic: Calculate the message authentication code (`mac`) and also append cookie value pub fn seal(&mut self, peer: PeerPtr, srv: &CryptoServer) -> Result<()> { - let mac = hash_domains::mac()? + let mac = hash_domains::mac(peer.get(srv).protocol_version.keyed_hash())? .mix(peer.get(srv).spkt.deref())? .mix(&self.as_bytes()[span_of!(Self, msg_type..mac)])?; self.mac.copy_from_slice(mac.into_value()[..16].as_ref()); @@ -3109,7 +3034,7 @@ where /// This is called inside [Self::seal] and does not need to be called again separately. pub fn seal_cookie(&mut self, peer: PeerPtr, srv: &CryptoServer) -> Result<()> { if let Some(cookie_key) = &peer.cv().get(srv) { - let cookie = hash_domains::cookie()? + let cookie = hash_domains::cookie(KeyedHash::keyed_shake256())? .mix(cookie_key.value.secret())? .mix(&self.as_bytes()[span_of!(Self, msg_type..cookie)])?; self.cookie @@ -3124,8 +3049,8 @@ where M: AsBytes + FromBytes, { /// Internal business logic: Check the message authentication code produced by [Self::seal] - pub fn check_seal(&self, srv: &CryptoServer) -> Result { - let expected = hash_domains::mac()? + pub fn check_seal(&self, srv: &CryptoServer, shake_or_blake: KeyedHash) -> Result { + let expected = hash_domains::mac(shake_or_blake)? .mix(srv.spkm.deref())? .mix(&self.as_bytes()[span_of!(Self, msg_type..mac)])?; Ok(constant_time::memcmp( @@ -3137,11 +3062,11 @@ where impl InitiatorHandshake { /// Zero initialization of an InitiatorHandshake, with up to date timestamp - pub fn zero_with_timestamp(srv: &CryptoServer) -> Self { + pub fn zero_with_timestamp(srv: &CryptoServer, keyed_hash: KeyedHash) -> Self { InitiatorHandshake { created_at: srv.timebase.now(), next: HandshakeStateMachine::RespHello, - core: HandshakeState::zero(), + core: HandshakeState::zero(keyed_hash), eski: ESk::zero(), epki: EPk::zero(), tx_at: 0.0, @@ -3156,38 +3081,49 @@ impl InitiatorHandshake { impl HandshakeState { /// Zero initialization of an HandshakeState - pub fn zero() -> Self { + pub fn zero(keyed_hash: KeyedHash) -> Self { Self { sidi: SessionId::zero(), sidr: SessionId::zero(), - ck: SecretHashDomain::zero().dup(), + ck: SecretHashDomain::zero(keyed_hash).dup(), } } /// Securely erase the chaining key pub fn erase(&mut self) { - self.ck = SecretHashDomain::zero().dup(); + self.ck = SecretHashDomain::zero(self.ck.keyed_hash().clone()).dup(); } /// Initialize the handshake state with the responder public key and the protocol domain /// separator pub fn init(&mut self, spkr: &[u8]) -> Result<&mut Self> { - self.ck = hash_domains::ckinit()?.turn_secret().mix(spkr)?.dup(); + self.ck = hash_domains::ckinit(self.ck.keyed_hash().clone())? + .turn_secret() + .mix(spkr)? + .dup(); Ok(self) } /// Mix some data into the chaining key. This is used for mixing cryptographic keys and public /// data alike into the chaining key pub fn mix(&mut self, a: &[u8]) -> Result<&mut Self> { - self.ck = self.ck.mix(&hash_domains::mix()?)?.mix(a)?.dup(); + self.ck = self + .ck + .mix(&hash_domains::mix(self.ck.keyed_hash().clone())?)? + .mix(a)? + .dup(); Ok(self) } /// Encrypt some data with a value derived from the current chaining key and mix that data /// into the protocol state. pub fn encrypt_and_mix(&mut self, ct: &mut [u8], pt: &[u8]) -> Result<&mut Self> { - let k = self.ck.mix(&hash_domains::hs_enc()?)?.into_secret(); - aead::encrypt(ct, k.secret(), &[0u8; aead::NONCE_LEN], &[], pt)?; + let k = self + .ck + .mix(&hash_domains::hs_enc(self.ck.keyed_hash().clone())?)? + .into_secret(); + ensure!(Aead::NONCE_LEN == 12); + Aead.encrypt(ct, k.secret(), &[0u8; 12], &[], pt)?; self.mix(ct) } @@ -3196,8 +3132,12 @@ impl HandshakeState { /// Makes sure that the same values are mixed into the chaining that where mixed in on the /// sender side. pub fn decrypt_and_mix(&mut self, pt: &mut [u8], ct: &[u8]) -> Result<&mut Self> { - let k = self.ck.mix(&hash_domains::hs_enc()?)?.into_secret(); - aead::decrypt(pt, k.secret(), &[0u8; aead::NONCE_LEN], &[], ct)?; + let k = self + .ck + .mix(&hash_domains::hs_enc(self.ck.keyed_hash().clone())?)? + .into_secret(); + ensure!(Aead::NONCE_LEN == 12); + Aead.decrypt(pt, k.secret(), &[0u8; 12], &[], ct)?; self.mix(ct) } @@ -3207,13 +3147,20 @@ impl HandshakeState { /// /// This is used to include asymmetric cryptography in the rosenpass protocol // I loathe "error: constant expression depends on a generic parameter" - pub fn encaps_and_mix, const SHK_LEN: usize>( + pub fn encaps_and_mix< + const KEM_SK_LEN: usize, + const KEM_PK_LEN: usize, + const KEM_CT_LEN: usize, + const KEM_SHK_LEN: usize, + KemImpl: Kem, + >( &mut self, - ct: &mut [u8], - pk: &[u8], + kem: &KemImpl, + ct: &mut [u8; KEM_CT_LEN], + pk: &[u8; KEM_PK_LEN], ) -> Result<&mut Self> { - let mut shk = Secret::::zero(); - T::encaps(shk.secret_mut(), ct, pk)?; + let mut shk = Secret::::zero(); + kem.encaps(shk.secret_mut(), ct, pk)?; self.mix(pk)?.mix(shk.secret())?.mix(ct) } @@ -3221,14 +3168,21 @@ impl HandshakeState { /// /// Makes sure that the same values are mixed into the chaining that where mixed in on the /// sender side. - pub fn decaps_and_mix, const SHK_LEN: usize>( + pub fn decaps_and_mix< + const KEM_SK_LEN: usize, + const KEM_PK_LEN: usize, + const KEM_CT_LEN: usize, + const KEM_SHK_LEN: usize, + KemImpl: Kem, + >( &mut self, - sk: &[u8], - pk: &[u8], - ct: &[u8], + kem: &KemImpl, + sk: &[u8; KEM_SK_LEN], + pk: &[u8; KEM_PK_LEN], + ct: &[u8; KEM_CT_LEN], ) -> Result<&mut Self> { - let mut shk = Secret::::zero(); - T::decaps(shk.secret_mut(), sk, ct)?; + let mut shk = Secret::::zero(); + kem.decaps(shk.secret_mut(), sk, ct)?; self.mix(pk)?.mix(shk.secret())?.mix(ct) } @@ -3259,7 +3213,7 @@ impl HandshakeState { .copy_from_slice(self.ck.clone().danger_into_secret().secret()); // calculate ad contents - let ad = hash_domains::biscuit_ad()? + let ad = hash_domains::biscuit_ad(peer.get(srv).protocol_version.keyed_hash())? .mix(srv.spkm.deref())? .mix(self.sidi.as_slice())? .mix(self.sidr.as_slice())? @@ -3277,7 +3231,7 @@ impl HandshakeState { let k = bk.get(srv).value.secret(); let pt = biscuit.as_bytes(); - xaead::encrypt(biscuit_ct, k, &*n, &ad, pt)?; + XAead.encrypt_with_nonce_in_ctxt(biscuit_ct, k, &*n, &ad, pt)?; self.mix(biscuit_ct) } @@ -3288,12 +3242,13 @@ impl HandshakeState { biscuit_ct: &[u8], sidi: SessionId, sidr: SessionId, + shake_or_blake: KeyedHash, ) -> Result<(PeerPtr, BiscuitId, HandshakeState)> { // The first bit of the biscuit indicates which biscuit key was used let bk = BiscuitKeyPtr(((biscuit_ct[0] & 0b1000_0000) >> 7) as usize); // Calculate additional data fields - let ad = hash_domains::biscuit_ad()? + let ad = hash_domains::biscuit_ad(shake_or_blake)? .mix(srv.spkm.deref())? .mix(sidi.as_slice())? .mix(sidr.as_slice())? @@ -3303,7 +3258,7 @@ impl HandshakeState { let mut biscuit = Secret::::zero(); // pt buf let mut biscuit: Ref<&mut [u8], Biscuit> = Ref::new(biscuit.secret_mut().as_mut_slice()).unwrap(); - xaead::decrypt( + XAead.decrypt_with_nonce_in_ctxt( biscuit.as_bytes_mut(), bk.get(srv).value.secret(), &ad, @@ -3312,18 +3267,21 @@ impl HandshakeState { // Reconstruct the biscuit fields let no = BiscuitId::from_slice(&biscuit.biscuit_no); - let ck = SecretHashDomain::danger_from_secret(Secret::from_slice(&biscuit.ck)).dup(); let pid = PeerId::from_slice(&biscuit.pidi); - - // Reconstruct the handshake state - let mut hs = Self { sidi, sidr, ck }; - hs.mix(biscuit_ct)?; - // Look up the associated peer let peer = srv .find_peer(pid) // TODO: FindPeer should return a Result<()> .with_context(|| format!("Could not decode biscuit for peer {pid:?}: No such peer."))?; + let ck = SecretHashDomain::danger_from_secret( + Secret::from_slice(&biscuit.ck), + peer.get(srv).protocol_version.keyed_hash(), + ) + .dup(); + // Reconstruct the handshake state + let mut hs = Self { sidi, sidr, ck }; + hs.mix(biscuit_ct)?; + Ok((peer, no, hs)) } @@ -3332,10 +3290,19 @@ impl HandshakeState { /// This called by either party. /// /// `role` indicates whether the local peer was an initiator or responder in the handshake. - pub fn enter_live(self, srv: &CryptoServer, role: HandshakeRole) -> Result { + pub fn enter_live( + self, + srv: &CryptoServer, + role: HandshakeRole, + either_shake_or_blake: KeyedHash, + ) -> Result { let HandshakeState { ck, sidi, sidr } = self; - let tki = ck.mix(&hash_domains::ini_enc()?)?.into_secret(); - let tkr = ck.mix(&hash_domains::res_enc()?)?.into_secret(); + let tki = ck + .mix(&hash_domains::ini_enc(either_shake_or_blake.clone())?)? + .into_secret(); + let tkr = ck + .mix(&hash_domains::res_enc(either_shake_or_blake)?)? + .into_secret(); let created_at = srv.timebase.now(); let (ntx, nrx) = (0, 0); let (mysid, peersid, ktx, krx) = match role { @@ -3357,64 +3324,138 @@ impl HandshakeState { } impl CryptoServer { + /// Variant of [Self::osk] that allows a custom, already compressed domain separator to be specified + /// + /// Refer to the documentation of [Self::osk] for more information. + pub fn osk_with_compressed_domain_separator( + &self, + peer: PeerPtr, + compressed_domain_separator: &PublicSymKey, + ) -> Result { + let session = peer + .session() + .get(self) + .as_ref() + .with_context(|| format!("No current session for peer {:?}", peer))?; + + Ok(session.ck.mix(compressed_domain_separator)?.into_secret()) + } + + /// Variant of [Self::osk] that allows a custom domain separator to be specified + /// + /// Refer to the documentation of [Self::osk] for more information. + pub fn osk_with_domain_separator( + &self, + peer: PeerPtr, + domain_separator: &OskDomainSeparator, + ) -> Result { + let hash_choice = peer.get(self).protocol_version.keyed_hash(); + let compressed_domain_separator = domain_separator.compress_with(hash_choice)?; + self.osk_with_compressed_domain_separator(peer, &compressed_domain_separator) + } + /// Get the shared key that was established with given peer /// /// Fail if no session is available with the peer /// + /// # See also + /// + /// - [Self::osk_with_domain_separator] + /// - [Self::osk_with_compressed_domain_separator] + /// /// # Examples /// /// See the example in [crate::protocol] for an incomplete but working example /// of how to perform a key exchange using Rosenpass. /// /// See the example in [CryptoServer::poll] for a complete example. + /// + /// See the documentation and examples in [super::osk_domain_separator] for more information + /// about using custom domain separators. pub fn osk(&self, peer: PeerPtr) -> Result { - let session = peer - .session() + let hash_choice = peer.get(self).protocol_version.keyed_hash(); + let compressed_domain_separator = peer .get(self) - .as_ref() - .with_context(|| format!("No current session for peer {:?}", peer))?; - Ok(session.ck.mix(&hash_domains::osk()?)?.into_secret()) + .osk_domain_separator + .compress_with(hash_choice)?; + self.osk_with_compressed_domain_separator(peer, &compressed_domain_separator) } } +/// Marks a section of the protocol using the same identifiers as are used in the whitepaper. +/// When building with the trace benchmarking feature enabled, this also emits span events into the +/// trace, which allows reconstructing the run times of the individual sections for performance +/// measurement. +macro_rules! protocol_section { + ($label:expr, $body:block) => {{ + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span($label); + + #[allow(unused_braces)] + $body + }}; +} + impl CryptoServer { /// Core cryptographic protocol implementation: Kicks of the handshake /// on the initiator side, producing the InitHello message. pub fn handle_initiation(&mut self, peer: PeerPtr, ih: &mut InitHello) -> Result { - let mut hs = InitiatorHandshake::zero_with_timestamp(self); + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span("handle_initiation"); + + let mut hs = InitiatorHandshake::zero_with_timestamp( + self, + peer.get(self).protocol_version.keyed_hash(), + ); // IHI1 - hs.core.init(peer.get(self).spkt.deref())?; + protocol_section!("IHI1", { + hs.core.init(peer.get(self).spkt.deref())?; + }); // IHI2 - hs.core.sidi.randomize(); - ih.sidi.copy_from_slice(&hs.core.sidi.value); + protocol_section!("IHI2", { + hs.core.sidi.randomize(); + ih.sidi.copy_from_slice(&hs.core.sidi.value); + }); // IHI3 - EphemeralKem::keygen(hs.eski.secret_mut(), &mut *hs.epki)?; - ih.epki.copy_from_slice(&hs.epki.value); + protocol_section!("IHI3", { + EphemeralKem.keygen(hs.eski.secret_mut(), &mut *hs.epki)?; + ih.epki.copy_from_slice(&hs.epki.value); + }); // IHI4 - hs.core.mix(ih.sidi.as_slice())?.mix(ih.epki.as_slice())?; + protocol_section!("IHI4", { + hs.core.mix(ih.sidi.as_slice())?.mix(ih.epki.as_slice())?; + }); // IHI5 - hs.core - .encaps_and_mix::( - ih.sctr.as_mut_slice(), - peer.get(self).spkt.deref(), - )?; + protocol_section!("IHI5", { + hs.core + .encaps_and_mix(&StaticKem, &mut ih.sctr, peer.get(self).spkt.deref())?; + }); // IHI6 - hs.core - .encrypt_and_mix(ih.pidic.as_mut_slice(), self.pidm()?.as_ref())?; + protocol_section!("IHI6", { + hs.core.encrypt_and_mix( + ih.pidic.as_mut_slice(), + self.pidm(peer.get(self).protocol_version.keyed_hash())? + .as_ref(), + )?; + }); // IHI7 - hs.core - .mix(self.spkm.deref())? - .mix(peer.get(self).psk.secret())?; + protocol_section!("IHI7", { + hs.core + .mix(self.spkm.deref())? + .mix(peer.get(self).psk.secret())?; + }); // IHI8 - hs.core.encrypt_and_mix(ih.auth.as_mut_slice(), &[])?; + protocol_section!("IHI8", { + hs.core.encrypt_and_mix(ih.auth.as_mut_slice(), &[])?; + }); // Update the handshake hash last (not changing any state on prior error peer.hs().insert(self, hs)?; @@ -3424,61 +3465,84 @@ impl CryptoServer { /// Core cryptographic protocol implementation: Parses an [InitHello] message and produces a /// [RespHello] message on the responder side. - pub fn handle_init_hello(&mut self, ih: &InitHello, rh: &mut RespHello) -> Result { - let mut core = HandshakeState::zero(); + pub fn handle_init_hello( + &mut self, + ih: &InitHello, + rh: &mut RespHello, + keyed_hash: KeyedHash, + ) -> Result { + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span("handle_init_hello"); + + let mut core = HandshakeState::zero(keyed_hash); core.sidi = SessionId::from_slice(&ih.sidi); // IHR1 - core.init(self.spkm.deref())?; + protocol_section!("IHR1", { + core.init(self.spkm.deref())?; + }); // IHR4 - core.mix(&ih.sidi)?.mix(&ih.epki)?; + protocol_section!("IHR4", { + core.mix(&ih.sidi)?.mix(&ih.epki)?; + }); // IHR5 - core.decaps_and_mix::( - self.sskm.secret(), - self.spkm.deref(), - &ih.sctr, - )?; + protocol_section!("IHR5", { + core.decaps_and_mix(&StaticKem, self.sskm.secret(), self.spkm.deref(), &ih.sctr)?; + }); // IHR6 - let peer = { + let peer = protocol_section!("IHR6", { let mut peerid = PeerId::zero(); core.decrypt_and_mix(&mut *peerid, &ih.pidic)?; self.find_peer(peerid) .with_context(|| format!("No such peer {peerid:?}."))? - }; + }); // IHR7 - core.mix(peer.get(self).spkt.deref())? - .mix(peer.get(self).psk.secret())?; + protocol_section!("IHR7", { + core.mix(peer.get(self).spkt.deref())? + .mix(peer.get(self).psk.secret())?; + }); // IHR8 - core.decrypt_and_mix(&mut [0u8; 0], &ih.auth)?; + protocol_section!("IHR8", { + core.decrypt_and_mix(&mut [0u8; 0], &ih.auth)?; + }); // RHR1 - core.sidr.randomize(); - rh.sidi.copy_from_slice(core.sidi.as_ref()); - rh.sidr.copy_from_slice(core.sidr.as_ref()); + protocol_section!("RHR1", { + core.sidr.randomize(); + rh.sidi.copy_from_slice(core.sidi.as_ref()); + rh.sidr.copy_from_slice(core.sidr.as_ref()); + }); // RHR3 - core.mix(&rh.sidr)?.mix(&rh.sidi)?; + protocol_section!("RHR3", { + core.mix(&rh.sidr)?.mix(&rh.sidi)?; + }); // RHR4 - core.encaps_and_mix::(&mut rh.ecti, &ih.epki)?; + protocol_section!("RHR4", { + core.encaps_and_mix(&EphemeralKem, &mut rh.ecti, &ih.epki)?; + }); // RHR5 - core.encaps_and_mix::( - &mut rh.scti, - peer.get(self).spkt.deref(), - )?; + protocol_section!("RHR5", { + core.encaps_and_mix(&StaticKem, &mut rh.scti, peer.get(self).spkt.deref())?; + }); // RHR6 - core.store_biscuit(self, peer, &mut rh.biscuit)?; + protocol_section!("RHR6", { + core.store_biscuit(self, peer, &mut rh.biscuit)?; + }); // RHR7 - core.encrypt_and_mix(&mut rh.auth, &[])?; + protocol_section!("RHR7", { + core.encrypt_and_mix(&mut rh.auth, &[])?; + }); Ok(peer) } @@ -3486,6 +3550,9 @@ impl CryptoServer { /// Core cryptographic protocol implementation: Parses an [RespHello] message and produces an /// [InitConf] message on the initiator side. pub fn handle_resp_hello(&mut self, rh: &RespHello, ic: &mut InitConf) -> Result { + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span("handle_resp_hello"); + // RHI2 let peer = self .lookup_handshake(SessionId::from_slice(&rh.sidi)) @@ -3529,27 +3596,34 @@ impl CryptoServer { // to save us from the repetitive secret unwrapping // RHI3 - core.mix(&rh.sidr)?.mix(&rh.sidi)?; + protocol_section!("RHI3", { + core.mix(&rh.sidr)?.mix(&rh.sidi)?; + }); // RHI4 - core.decaps_and_mix::( - hs!().eski.secret(), - hs!().epki.deref(), - &rh.ecti, - )?; + protocol_section!("RHI4", { + core.decaps_and_mix( + &EphemeralKem, + hs!().eski.secret(), + hs!().epki.deref(), + &rh.ecti, + )?; + }); // RHI5 - core.decaps_and_mix::( - self.sskm.secret(), - self.spkm.deref(), - &rh.scti, - )?; + protocol_section!("RHI5", { + core.decaps_and_mix(&StaticKem, self.sskm.secret(), self.spkm.deref(), &rh.scti)?; + }); // RHI6 - core.mix(&rh.biscuit)?; + protocol_section!("RHI6", { + core.mix(&rh.biscuit)?; + }); // RHI7 - core.decrypt_and_mix(&mut [0u8; 0], &rh.auth)?; + protocol_section!("RHI7", { + core.decrypt_and_mix(&mut [0u8; 0], &rh.auth)?; + }); // TODO: We should just authenticate the entire network package up to the auth // tag as a pattern instead of mixing in fields separately @@ -3558,48 +3632,77 @@ impl CryptoServer { ic.sidr.copy_from_slice(&rh.sidr); // ICI3 - core.mix(&ic.sidi)?.mix(&ic.sidr)?; - ic.biscuit.copy_from_slice(&rh.biscuit); + protocol_section!("ICI3", { + core.mix(&ic.sidi)?.mix(&ic.sidr)?; + ic.biscuit.copy_from_slice(&rh.biscuit); + }); // ICI4 - core.encrypt_and_mix(&mut ic.auth, &[])?; + protocol_section!("ICI4", { + core.encrypt_and_mix(&mut ic.auth, &[])?; + }); // Split() – We move the secrets into the session; we do not // delete the InitiatorHandshake, just clear it's secrets because // we still need it for InitConf message retransmission to function. // ICI7 - peer.session() - .insert(self, core.enter_live(self, HandshakeRole::Initiator)?)?; - hs_mut!().core.erase(); - hs_mut!().next = HandshakeStateMachine::RespConf; + protocol_section!("ICI7", { + peer.session().insert( + self, + core.enter_live( + self, + HandshakeRole::Initiator, + peer.get(self).protocol_version.keyed_hash(), + )?, + )?; + hs_mut!().core.erase(); + hs_mut!().next = HandshakeStateMachine::RespConf; + }); Ok(peer) } /// Core cryptographic protocol implementation: Parses an [InitConf] message and produces an - /// [EmptyData] (responder confimation) message on the responder side. + /// [EmptyData] (responder confirmation) message on the responder side. /// /// This concludes the handshake on the cryptographic level; the [EmptyData] message is just /// an acknowledgement message telling the initiator to stop performing retransmissions. - pub fn handle_init_conf(&mut self, ic: &InitConf, rc: &mut EmptyData) -> Result { + pub fn handle_init_conf( + &mut self, + ic: &InitConf, + rc: &mut EmptyData, + keyed_hash: KeyedHash, + ) -> Result { + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span("handle_init_conf"); + // (peer, bn) ← LoadBiscuit(InitConf.biscuit) // ICR1 - let (peer, biscuit_no, mut core) = HandshakeState::load_biscuit( - self, - &ic.biscuit, - SessionId::from_slice(&ic.sidi), - SessionId::from_slice(&ic.sidr), - )?; + let (peer, biscuit_no, mut core) = protocol_section!("ICR1", { + HandshakeState::load_biscuit( + self, + &ic.biscuit, + SessionId::from_slice(&ic.sidi), + SessionId::from_slice(&ic.sidr), + keyed_hash, + )? + }); // ICR2 - core.encrypt_and_mix(&mut [0u8; aead::TAG_LEN], &[])?; + protocol_section!("ICR2", { + core.encrypt_and_mix(&mut [0u8; Aead::TAG_LEN], &[])?; + }); // ICR3 - core.mix(&ic.sidi)?.mix(&ic.sidr)?; + protocol_section!("ICR3", { + core.mix(&ic.sidi)?.mix(&ic.sidr)?; + }); // ICR4 - core.decrypt_and_mix(&mut [0u8; 0], &ic.auth)?; + protocol_section!("ICR4", { + core.decrypt_and_mix(&mut [0u8; 0], &ic.auth)?; + }); // ICR5 // Defense against replay attacks; implementations may accept @@ -3611,14 +3714,24 @@ impl CryptoServer { ); // ICR6 - peer.get_mut(self).biscuit_used = biscuit_no; + protocol_section!("ICR6", { + peer.get_mut(self).biscuit_used = biscuit_no; + }); // ICR7 - peer.session() - .insert(self, core.enter_live(self, HandshakeRole::Responder)?)?; - // TODO: This should be part of the protocol specification. - // Abort any ongoing handshake from initiator role - peer.hs().take(self); + protocol_section!("ICR7", { + peer.session().insert( + self, + core.enter_live( + self, + HandshakeRole::Responder, + peer.get(self).protocol_version.keyed_hash(), + )?, + )?; + // TODO: This should be part of the protocol specification. + // Abort any ongoing handshake from initiator role + peer.hs().take(self); + }); // TODO: Implementing RP should be possible without touching the live session stuff // TODO: I fear that this may lead to race conditions; the acknowledgement may be @@ -3652,9 +3765,9 @@ impl CryptoServer { rc.ctr.copy_from_slice(&ses.txnm.to_le_bytes()); ses.txnm += 1; // Increment nonce before encryption, just in case an error is raised - let n = cat!(aead::NONCE_LEN; &rc.ctr, &[0u8; 4]); + let n = cat!(Aead::NONCE_LEN; &rc.ctr, &[0u8; 4]); let k = ses.txkm.secret(); - aead::encrypt(&mut rc.auth, k, &n, &[], &[])?; // ct, k, n, ad, pt + Aead.encrypt(&mut rc.auth, k, &n, &[], &[])?; // ct, k, n, ad, pt Ok(peer) } @@ -3663,11 +3776,23 @@ impl CryptoServer { /// message then terminates the handshake. /// /// The EmptyData message is just there to tell the initiator to abort retransmissions. - pub fn handle_resp_conf(&mut self, rc: &EmptyData) -> Result { + pub fn handle_resp_conf( + &mut self, + msg_in: &Ref<&[u8], Envelope>, + seal_broken: String, + ) -> Result { + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span("handle_resp_conf"); + + let rc: &EmptyData = &msg_in.payload; let sid = SessionId::from_slice(&rc.sid); let hs = self .lookup_handshake(sid) .with_context(|| format!("Got RespConf packet for non-existent session {sid:?}"))?; + ensure!( + msg_in.check_seal(self, hs.peer().get(self).protocol_version.keyed_hash())?, + seal_broken + ); let ses = hs.peer().session(); let exp = hs.get(self).as_ref().map(|h| h.next); @@ -3685,16 +3810,16 @@ impl CryptoServer { let s = ses.get_mut(self).as_mut().with_context(|| { format!("Cannot validate EmptyData message. Missing encryption session for {sid:?}") })?; - // the unwrap can not fail, because the slice returned by ctr() is + // the unwrapping can not fail, because the slice returned by ctr() is // guaranteed to have the correct size let n = u64::from_le_bytes(rc.ctr); ensure!(n >= s.txnt, "Stale nonce"); s.txnt = n; - aead::decrypt( + Aead.decrypt( // pt, k, n, ad, ct &mut [0u8; 0], s.txkt.secret(), - &cat!(aead::NONCE_LEN; &rc.ctr, &[0u8; 4]), + &cat!(Aead::NONCE_LEN; &rc.ctr, &[0u8; 4]), &[], &rc.auth, )?; @@ -3712,6 +3837,9 @@ impl CryptoServer { /// /// See more on DOS mitigation in Rosenpass in the [whitepaper](https://rosenpass.eu/whitepaper.pdf). pub fn handle_cookie_reply(&mut self, cr: &CookieReply) -> Result { + #[cfg(feature = "trace_bench")] + let _span_guard = rosenpass_util::trace_bench::trace().emit_span("handle_cookie_reply"); + let peer_ptr: Option = self .lookup_session(Public::new(cr.inner.sid)) .map(|v| PeerPtr(v.0)) @@ -3750,12 +3878,19 @@ impl CryptoServer { }?; let spkt = peer.get(self).spkt.deref(); - let cookie_key = hash_domains::cookie_key()?.mix(spkt)?.into_value(); + let cookie_key = hash_domains::cookie_key(KeyedHash::keyed_shake256())? + .mix(spkt)? + .into_value(); let cookie_value = peer.cv().update_mut(self).unwrap(); - xaead::decrypt(cookie_value, &cookie_key, &mac, &cr.inner.cookie_encrypted)?; + XAead.decrypt_with_nonce_in_ctxt( + cookie_value, + &cookie_key, + &mac, + &cr.inner.cookie_encrypted, + )?; - // Immediately retransmit on recieving a cookie reply message + // Immediately retransmit on receiving a cookie reply message peer.hs().register_immediate_retransmission(self)?; Ok(peer) @@ -3770,658 +3905,3 @@ impl CryptoServer { } } } - -/// Used to parse a network message using [zerocopy] -fn truncating_cast_into(buf: &mut [u8]) -> Result, RosenpassError> { - Ref::new(&mut buf[..size_of::()]).ok_or(RosenpassError::BufferSizeMismatch) -} - -/// Used to parse a network message using [zerocopy], mutably -pub fn truncating_cast_into_nomut( - buf: &[u8], -) -> Result, RosenpassError> { - Ref::new(&buf[..size_of::()]).ok_or(RosenpassError::BufferSizeMismatch) -} - -pub mod testutils { - use std::ops::DerefMut; - - use super::*; - - /// Helper for tests and examples - pub struct ServerForTesting { - pub peer: PeerPtr, - pub peer_keys: (SSk, SPk), - pub srv: CryptoServer, - } - - impl ServerForTesting { - pub fn new() -> anyhow::Result { - let (mut sskm, mut spkm) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(sskm.secret_mut(), spkm.deref_mut())?; - let mut srv = CryptoServer::new(sskm, spkm); - - let (mut sskt, mut spkt) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(sskt.secret_mut(), spkt.deref_mut())?; - let peer = srv.add_peer(None, spkt.clone())?; - - let peer_keys = (sskt, spkt); - Ok(ServerForTesting { - peer, - peer_keys, - srv, - }) - } - - pub fn tuple(self) -> (PeerPtr, (SSk, SPk), CryptoServer) { - (self.peer, self.peer_keys, self.srv) - } - } - - /// Time travel forward in time - pub fn time_travel_forward(srv: &mut CryptoServer, secs: f64) { - let dur = std::time::Duration::from_secs_f64(secs); - srv.timebase.0 = srv.timebase.0.checked_sub(dur).unwrap(); - } -} - -#[cfg(test)] -mod test { - use std::{borrow::BorrowMut, net::SocketAddrV4, ops::DerefMut, thread::sleep, time::Duration}; - - use super::*; - use serial_test::serial; - use zerocopy::FromZeroes; - - struct VecHostIdentifier(Vec); - - impl HostIdentification for VecHostIdentifier { - fn encode(&self) -> &[u8] { - &self.0 - } - } - - impl Display for VecHostIdentifier { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self.0) - } - } - - impl From> for VecHostIdentifier { - fn from(v: Vec) -> Self { - VecHostIdentifier(v) - } - } - - fn setup_logging() { - use std::io::Write; - let mut log_builder = env_logger::Builder::from_default_env(); // sets log level filter from environment (or defaults) - log_builder.filter_level(log::LevelFilter::Info); - log_builder.format_timestamp_nanos(); - log_builder.format(|buf, record| { - let ts_format = buf.timestamp_nanos().to_string(); - writeln!(buf, "{}: {}", &ts_format[14..], record.args()) - }); - - let _ = log_builder.try_init(); - } - - #[test] - #[serial] - /// Ensure that the protocol implementation can deal with truncated - /// messages and with overlong messages. - /// - /// This test performs a complete handshake between two randomly generated - /// servers; instead of delivering the message correctly at first messages - /// of length zero through about 1.2 times the correct message size are delivered. - /// - /// Producing an error is expected on each of these messages. - /// - /// Finally the correct message is delivered and the same process - /// starts again in the other direction. - /// - /// Through all this, the handshake should still successfully terminate; - /// i.e. an exchanged key must be produced in both servers. - fn handles_incorrect_size_messages() { - setup_logging(); - rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - stacker::grow(8 * 1024 * 1024, || { - const OVERSIZED_MESSAGE: usize = ((MAX_MESSAGE_LEN as f32) * 1.2) as usize; - type MsgBufPlus = Public; - - const PEER0: PeerPtr = PeerPtr(0); - - let (mut me, mut they) = make_server_pair().unwrap(); - let (mut msgbuf, mut resbuf) = (MsgBufPlus::zero(), MsgBufPlus::zero()); - - // Process the entire handshake - let mut msglen = Some(me.initiate_handshake(PEER0, &mut *resbuf).unwrap()); - while let Some(l) = msglen { - std::mem::swap(&mut me, &mut they); - std::mem::swap(&mut msgbuf, &mut resbuf); - msglen = test_incorrect_sizes_for_msg(&mut me, &*msgbuf, l, &mut *resbuf); - } - - assert_eq!( - me.osk(PEER0).unwrap().secret(), - they.osk(PEER0).unwrap().secret() - ); - }); - } - - /// Used in handles_incorrect_size_messages() to first deliver many truncated - /// and overlong messages, finally the correct message is delivered and the response - /// returned. - fn test_incorrect_sizes_for_msg( - srv: &mut CryptoServer, - msgbuf: &[u8], - msglen: usize, - resbuf: &mut [u8], - ) -> Option { - resbuf.fill(0); - - for l in 0..(((msglen as f32) * 1.2) as usize) { - if l == msglen { - continue; - } - - let res = srv.handle_msg(&msgbuf[..l], resbuf); - assert!(res.is_err()); // handle_msg should raise an error - assert!(!resbuf.iter().any(|x| *x != 0)); // resbuf should not have been changed - } - - // Apply the proper handle_msg operation - srv.handle_msg(&msgbuf[..msglen], resbuf).unwrap().resp - } - - fn keygen() -> Result<(SSk, SPk)> { - // TODO: Copied from the benchmark; deduplicate - let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(sk.secret_mut(), pk.deref_mut())?; - Ok((sk, pk)) - } - - fn make_server_pair() -> Result<(CryptoServer, CryptoServer)> { - // TODO: Copied from the benchmark; deduplicate - let psk = SymKey::random(); - let ((ska, pka), (skb, pkb)) = (keygen()?, keygen()?); - let (mut a, mut b) = ( - CryptoServer::new(ska, pka.clone()), - CryptoServer::new(skb, pkb.clone()), - ); - a.add_peer(Some(psk.clone()), pkb)?; - b.add_peer(Some(psk), pka)?; - Ok((a, b)) - } - - #[test] - #[serial] - fn test_regular_exchange() { - setup_logging(); - rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - stacker::grow(8 * 1024 * 1024, || { - type MsgBufPlus = Public; - let (mut a, mut b) = make_server_pair().unwrap(); - - let mut a_to_b_buf = MsgBufPlus::zero(); - let mut b_to_a_buf = MsgBufPlus::zero(); - - let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); - let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); - ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); - - let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); - - let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); - - let init_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); - assert_eq!(init_msg_type, MsgType::InitHello); - - //B handles InitHello, sends RespHello - let HandleMsgResult { resp, .. } = b - .handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf) - .unwrap(); - - let resp_hello_len = resp.unwrap(); - - let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - assert_eq!(resp_msg_type, MsgType::RespHello); - - let HandleMsgResult { - resp, - exchanged_with, - } = a - .handle_msg(&b_to_a_buf[..resp_hello_len], &mut *a_to_b_buf) - .unwrap(); - - let init_conf_len = resp.unwrap(); - let init_conf_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); - - assert_eq!(exchanged_with, Some(PeerPtr(0))); - assert_eq!(init_conf_msg_type, MsgType::InitConf); - - //B handles InitConf, sends EmptyData - let HandleMsgResult { - resp: _, - exchanged_with, - } = b - .handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf) - .unwrap(); - - let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - - assert_eq!(exchanged_with, Some(PeerPtr(0))); - assert_eq!(empty_data_msg_type, MsgType::EmptyData); - }); - } - - #[test] - #[serial] - fn test_regular_init_conf_retransmit() { - setup_logging(); - rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - stacker::grow(8 * 1024 * 1024, || { - type MsgBufPlus = Public; - let (mut a, mut b) = make_server_pair().unwrap(); - - let mut a_to_b_buf = MsgBufPlus::zero(); - let mut b_to_a_buf = MsgBufPlus::zero(); - - let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); - let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); - ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); - - let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); - - let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); - - let init_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); - assert_eq!(init_msg_type, MsgType::InitHello); - - //B handles InitHello, sends RespHello - let HandleMsgResult { resp, .. } = b - .handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf) - .unwrap(); - - let resp_hello_len = resp.unwrap(); - - let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - assert_eq!(resp_msg_type, MsgType::RespHello); - - //A handles RespHello, sends InitConf, exchanges keys - let HandleMsgResult { - resp, - exchanged_with, - } = a - .handle_msg(&b_to_a_buf[..resp_hello_len], &mut *a_to_b_buf) - .unwrap(); - - let init_conf_len = resp.unwrap(); - let init_conf_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); - - assert_eq!(exchanged_with, Some(PeerPtr(0))); - assert_eq!(init_conf_msg_type, MsgType::InitConf); - - //B handles InitConf, sends EmptyData - let HandleMsgResult { - resp: _, - exchanged_with, - } = b - .handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf) - .unwrap(); - - let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - - assert_eq!(exchanged_with, Some(PeerPtr(0))); - assert_eq!(empty_data_msg_type, MsgType::EmptyData); - - //B handles InitConf again, sends EmptyData - let HandleMsgResult { - resp: _, - exchanged_with, - } = b - .handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf) - .unwrap(); - - let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - - assert!(exchanged_with.is_none()); - assert_eq!(empty_data_msg_type, MsgType::EmptyData); - }); - } - - #[test] - #[serial] - fn cookie_reply_mechanism_responder_under_load() { - setup_logging(); - rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - stacker::grow(8 * 1024 * 1024, || { - type MsgBufPlus = Public; - let (mut a, mut b) = make_server_pair().unwrap(); - - let mut a_to_b_buf = MsgBufPlus::zero(); - let mut b_to_a_buf = MsgBufPlus::zero(); - - let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); - let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); - ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); - - let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); - - let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); - let socket_addr_a = std::net::SocketAddr::V4(ip_a); - let mut ip_addr_port_a = match socket_addr_a.ip() { - std::net::IpAddr::V4(ipv4) => ipv4.octets().to_vec(), - std::net::IpAddr::V6(ipv6) => ipv6.octets().to_vec(), - }; - - ip_addr_port_a.extend_from_slice(&socket_addr_a.port().to_be_bytes()); - - let ip_addr_port_a: VecHostIdentifier = ip_addr_port_a.into(); - - //B handles handshake under load, should send cookie reply message with invalid cookie - let HandleMsgResult { resp, .. } = b - .handle_msg_under_load( - &a_to_b_buf.as_slice()[..init_hello_len], - &mut *b_to_a_buf, - &ip_addr_port_a, - ) - .unwrap(); - - let cookie_reply_len = resp.unwrap(); - - //A handles cookie reply message - a.handle_msg(&b_to_a_buf[..cookie_reply_len], &mut *a_to_b_buf) - .unwrap(); - - assert_eq!(PeerPtr(0).cv().lifecycle(&a), Lifecycle::Young); - - let expected_cookie_value = hash_domains::cookie_value() - .unwrap() - .mix( - b.active_or_retired_cookie_secrets()[0] - .unwrap() - .get(&b) - .value - .secret(), - ) - .unwrap() - .mix(ip_addr_port_a.encode()) - .unwrap() - .into_value()[..16] - .to_vec(); - - assert_eq!( - PeerPtr(0).cv().get(&a).map(|x| &x.value.secret()[..]), - Some(&expected_cookie_value[..]) - ); - - let retx_init_hello_len = loop { - match a.poll().unwrap() { - PollResult::SendRetransmission(peer) => { - break (a.retransmit_handshake(peer, &mut *a_to_b_buf).unwrap()); - } - PollResult::Sleep(time) => { - sleep(Duration::from_secs_f64(time)); - } - _ => {} - } - }; - - let retx_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); - assert_eq!(retx_msg_type, MsgType::InitHello); - - //B handles retransmitted message - let HandleMsgResult { resp, .. } = b - .handle_msg_under_load( - &a_to_b_buf.as_slice()[..retx_init_hello_len], - &mut *b_to_a_buf, - &ip_addr_port_a, - ) - .unwrap(); - - let _resp_hello_len = resp.unwrap(); - - let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - assert_eq!(resp_msg_type, MsgType::RespHello); - }); - } - - #[test] - #[serial] - fn cookie_reply_mechanism_initiator_bails_on_message_under_load() { - setup_logging(); - rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - stacker::grow(8 * 1024 * 1024, || { - type MsgBufPlus = Public; - let (mut a, mut b) = make_server_pair().unwrap(); - - let mut a_to_b_buf = MsgBufPlus::zero(); - let mut b_to_a_buf = MsgBufPlus::zero(); - - let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); - let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); - ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); - let ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); - - //A initiates handshake - let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); - - //B handles InitHello message, should respond with RespHello - let HandleMsgResult { resp, .. } = b - .handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf) - .unwrap(); - - let resp_hello_len = resp.unwrap(); - let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); - assert_eq!(resp_msg_type, MsgType::RespHello); - - let socket_addr_b = std::net::SocketAddr::V4(ip_b); - let mut ip_addr_port_b = [0u8; 18]; - let mut ip_addr_port_b_len = 0; - match socket_addr_b.ip() { - std::net::IpAddr::V4(ipv4) => { - ip_addr_port_b[0..4].copy_from_slice(&ipv4.octets()); - ip_addr_port_b_len += 4; - } - std::net::IpAddr::V6(ipv6) => { - ip_addr_port_b[0..16].copy_from_slice(&ipv6.octets()); - ip_addr_port_b_len += 16; - } - }; - - ip_addr_port_b[ip_addr_port_b_len..ip_addr_port_b_len + 2] - .copy_from_slice(&socket_addr_b.port().to_be_bytes()); - ip_addr_port_b_len += 2; - - let ip_addr_port_b: VecHostIdentifier = - ip_addr_port_b[..ip_addr_port_b_len].to_vec().into(); - - //A handles RespHello message under load, should not send cookie reply - assert!(a - .handle_msg_under_load( - &b_to_a_buf[..resp_hello_len], - &mut *a_to_b_buf, - &ip_addr_port_b - ) - .is_err()); - }); - } - - #[test] - fn init_conf_retransmission() -> anyhow::Result<()> { - rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); - - fn keypair() -> anyhow::Result<(SSk, SPk)> { - let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(sk.secret_mut(), pk.deref_mut())?; - Ok((sk, pk)) - } - - fn proc_initiation( - srv: &mut CryptoServer, - peer: PeerPtr, - ) -> anyhow::Result> { - let mut buf = MsgBuf::zero(); - srv.initiate_handshake(peer, buf.as_mut_slice())? - .discard_result(); - let msg = truncating_cast_into::>(buf.borrow_mut())?; - Ok(msg.read()) - } - - fn proc_msg( - srv: &mut CryptoServer, - rx: &Envelope, - ) -> anyhow::Result> { - let mut buf = MsgBuf::zero(); - srv.handle_msg(rx.as_bytes(), buf.as_mut_slice())? - .resp - .context("Failed to produce RespHello message")? - .discard_result(); - let msg = truncating_cast_into::>(buf.borrow_mut())?; - Ok(msg.read()) - } - - fn proc_init_hello( - srv: &mut CryptoServer, - ih: &Envelope, - ) -> anyhow::Result> { - proc_msg::(srv, ih) - } - - fn proc_resp_hello( - srv: &mut CryptoServer, - rh: &Envelope, - ) -> anyhow::Result> { - proc_msg::(srv, rh) - } - - fn proc_init_conf( - srv: &mut CryptoServer, - rh: &Envelope, - ) -> anyhow::Result> { - proc_msg::(srv, rh) - } - - fn poll(srv: &mut CryptoServer) -> anyhow::Result<()> { - // Discard all events; just apply the side effects - while !matches!(srv.poll()?, PollResult::Sleep(_)) {} - Ok(()) - } - - // TODO: Implement Clone on our message types - fn clone_msg(msg: &Msg) -> anyhow::Result { - Ok(truncating_cast_into_nomut::(msg.as_bytes())?.read()) - } - - fn break_payload( - srv: &mut CryptoServer, - peer: PeerPtr, - msg: &Envelope, - ) -> anyhow::Result> { - let mut msg = clone_msg(msg)?; - msg.as_bytes_mut()[memoffset::offset_of!(Envelope, payload)] ^= 0x01; - msg.seal(peer, srv)?; // Recalculate seal; we do not want to focus on "seal broken" errs - Ok(msg) - } - - fn check_faulty_proc_init_conf(srv: &mut CryptoServer, ic_broken: &Envelope) { - let mut buf = MsgBuf::zero(); - let res = srv.handle_msg(ic_broken.as_bytes(), buf.as_mut_slice()); - assert!(res.is_err()); - } - - fn check_retransmission( - srv: &mut CryptoServer, - ic: &Envelope, - ic_broken: &Envelope, - rc: &Envelope, - ) -> anyhow::Result<()> { - // Processing the same RespHello package again leads to retransmission (i.e. exactly the - // same output) - let rc_dup = proc_init_conf(srv, ic)?; - assert_eq!(rc.as_bytes(), rc_dup.as_bytes()); - - // Though if we directly call handle_resp_hello() we get an error since - // retransmission is not being handled by the cryptographic code - let mut discard_resp_conf = EmptyData::new_zeroed(); - let res = srv.handle_init_conf(&ic.payload, &mut discard_resp_conf); - assert!(res.is_err()); - - // Obviously, a broken InitConf message should still be rejected - check_faulty_proc_init_conf(srv, ic_broken); - - Ok(()) - } - - let (ska, pka) = keypair()?; - let (skb, pkb) = keypair()?; - - // initialize server and a pre-shared key - let mut a = CryptoServer::new(ska, pka.clone()); - let mut b = CryptoServer::new(skb, pkb.clone()); - - // introduce peers to each other - let b_peer = a.add_peer(None, pkb)?; - let a_peer = b.add_peer(None, pka)?; - - // Execute protocol up till the responder confirmation (EmptyData) - let ih1 = proc_initiation(&mut a, b_peer)?; - let rh1 = proc_init_hello(&mut b, &ih1)?; - let ic1 = proc_resp_hello(&mut a, &rh1)?; - let rc1 = proc_init_conf(&mut b, &ic1)?; - - // Modified version of ic1 and rc1, for tests that require it - let ic1_broken = break_payload(&mut a, b_peer, &ic1)?; - assert_ne!(ic1.as_bytes(), ic1_broken.as_bytes()); - - // Modified version of rc1, for tests that require it - let rc1_broken = break_payload(&mut b, a_peer, &rc1)?; - assert_ne!(rc1.as_bytes(), rc1_broken.as_bytes()); - - // Retransmission works as designed - check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; - - // Even with a couple of poll operations in between (which clears the cache - // after a time out of two minutes…we should never hit this time out in this - // cache) - for _ in 0..4 { - poll(&mut b)?; - check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; - } - - // We can even validate that the data is coming out of the cache by changing the cache - // to use our broken messages. It does not matter that these messages are cryptographically - // broken since we insert them manually into the cache - // a_peer.known_init_conf_response() - KnownInitConfResponsePtr::insert_for_request_msg( - &mut b, - a_peer, - &ic1_broken, - rc1_broken.clone(), - ); - check_retransmission(&mut b, &ic1_broken, &ic1, &rc1_broken)?; - - // Lets reset to the correct message though - KnownInitConfResponsePtr::insert_for_request_msg(&mut b, a_peer, &ic1, rc1.clone()); - - // Again, nothing changes after calling poll - poll(&mut b)?; - check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; - - // Except if we jump forward into the future past the point where the responder - // starts to initiate rekeying; in this case, the automatic time out is triggered and the cache is cleared - super::testutils::time_travel_forward(&mut b, REKEY_AFTER_TIME_RESPONDER); - - // As long as we do not call poll, everything is fine - check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; - - // But after we do, the response is gone and can not be recreated - // since the biscuit is stale - poll(&mut b)?; - check_faulty_proc_init_conf(&mut b, &ic1); // ic1 is now effectively broken - assert!(b.peers[0].known_init_conf_response.is_none()); // The cache is gone - - Ok(()) - } -} diff --git a/rosenpass/src/protocol/test.rs b/rosenpass/src/protocol/test.rs new file mode 100644 index 00000000..8bd17f91 --- /dev/null +++ b/rosenpass/src/protocol/test.rs @@ -0,0 +1,703 @@ +use std::{borrow::BorrowMut, fmt::Display, net::SocketAddrV4, ops::DerefMut}; + +use anyhow::{Context, Result}; +use serial_test::serial; +use zerocopy::{AsBytes, FromBytes, FromZeroes}; + +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; +use rosenpass_secret_memory::Public; +use rosenpass_util::mem::DiscardResultExt; + +use crate::msgs::{EmptyData, Envelope, InitConf, InitHello, MsgType, RespHello, MAX_MESSAGE_LEN}; + +use super::basic_types::{MsgBuf, SPk, SSk, SymKey}; +use super::constants::REKEY_AFTER_TIME_RESPONDER; +use super::osk_domain_separator::OskDomainSeparator; +use super::zerocopy::{truncating_cast_into, truncating_cast_into_nomut}; +use super::{ + CryptoServer, HandleMsgResult, HostIdentification, KnownInitConfResponsePtr, PeerPtr, + PollResult, ProtocolVersion, +}; + +struct VecHostIdentifier(Vec); + +impl HostIdentification for VecHostIdentifier { + fn encode(&self) -> &[u8] { + &self.0 + } +} + +impl Display for VecHostIdentifier { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self.0) + } +} + +impl From> for VecHostIdentifier { + fn from(v: Vec) -> Self { + VecHostIdentifier(v) + } +} + +fn setup_logging() { + use std::io::Write; + let mut log_builder = env_logger::Builder::from_default_env(); // sets log level filter from environment (or defaults) + log_builder.filter_level(log::LevelFilter::Info); + log_builder.format_timestamp_nanos(); + log_builder.format(|buf, record| { + let ts_format = buf.timestamp_nanos().to_string(); + writeln!(buf, "{}: {}", &ts_format[14..], record.args()) + }); + + let _ = log_builder.try_init(); +} + +#[test] +#[serial] +fn handles_incorrect_size_messages_v02() { + handles_incorrect_size_messages(ProtocolVersion::V02) +} + +#[test] +#[serial] +fn handles_incorrect_size_messages_v03() { + handles_incorrect_size_messages(ProtocolVersion::V03) +} + +/// Ensure that the protocol implementation can deal with truncated +/// messages and with overlong messages. +/// +/// This test performs a complete handshake between two randomly generated +/// servers; instead of delivering the message correctly at first messages +/// of length zero through about 1.2 times the correct message size are delivered. +/// +/// Producing an error is expected on each of these messages. +/// +/// Finally the correct message is delivered and the same process +/// starts again in the other direction. +/// +/// Through all this, the handshake should still successfully terminate; +/// i.e. an exchanged key must be produced in both servers. +fn handles_incorrect_size_messages(protocol_version: ProtocolVersion) { + setup_logging(); + rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); + stacker::grow(8 * 1024 * 1024, || { + const OVERSIZED_MESSAGE: usize = ((MAX_MESSAGE_LEN as f32) * 1.2) as usize; + type MsgBufPlus = Public; + + const PEER0: PeerPtr = PeerPtr(0); + + let (mut me, mut they) = make_server_pair(protocol_version).unwrap(); + let (mut msgbuf, mut resbuf) = (MsgBufPlus::zero(), MsgBufPlus::zero()); + + // Process the entire handshake + let mut msglen = Some(me.initiate_handshake(PEER0, &mut *resbuf).unwrap()); + while let Some(l) = msglen { + std::mem::swap(&mut me, &mut they); + std::mem::swap(&mut msgbuf, &mut resbuf); + msglen = test_incorrect_sizes_for_msg(&mut me, &*msgbuf, l, &mut *resbuf); + } + + assert_eq!( + me.osk(PEER0).unwrap().secret(), + they.osk(PEER0).unwrap().secret() + ); + }); +} + +/// Used in handles_incorrect_size_messages() to first deliver many truncated +/// and overlong messages, finally the correct message is delivered and the response +/// returned. +fn test_incorrect_sizes_for_msg( + srv: &mut CryptoServer, + msgbuf: &[u8], + msglen: usize, + resbuf: &mut [u8], +) -> Option { + resbuf.fill(0); + + for l in 0..(((msglen as f32) * 1.2) as usize) { + if l == msglen { + continue; + } + + let res = srv.handle_msg(&msgbuf[..l], resbuf); + assert!(res.is_err()); // handle_msg should raise an error + assert!(!resbuf.iter().any(|x| *x != 0)); // resbuf should not have been changed + } + + // Apply the proper handle_msg operation + srv.handle_msg(&msgbuf[..msglen], resbuf).unwrap().resp +} + +fn keygen() -> Result<(SSk, SPk)> { + // TODO: Copied from the benchmark; deduplicate + let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); + StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?; + Ok((sk, pk)) +} + +fn make_server_pair(protocol_version: ProtocolVersion) -> Result<(CryptoServer, CryptoServer)> { + // TODO: Copied from the benchmark; deduplicate + let psk = SymKey::random(); + let ((ska, pka), (skb, pkb)) = (keygen()?, keygen()?); + let (mut a, mut b) = ( + CryptoServer::new(ska, pka.clone()), + CryptoServer::new(skb, pkb.clone()), + ); + a.add_peer( + Some(psk.clone()), + pkb, + protocol_version.clone(), + OskDomainSeparator::default(), + )?; + b.add_peer( + Some(psk), + pka, + protocol_version, + OskDomainSeparator::default(), + )?; + Ok((a, b)) +} + +#[test] +#[serial] +fn test_regular_exchange_v02() { + test_regular_exchange(ProtocolVersion::V02) +} + +#[test] +#[serial] +fn test_regular_exchange_v03() { + test_regular_exchange(ProtocolVersion::V03) +} + +fn test_regular_exchange(protocol_version: ProtocolVersion) { + setup_logging(); + rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); + stacker::grow(8 * 1024 * 1024, || { + type MsgBufPlus = Public; + let (mut a, mut b) = make_server_pair(protocol_version).unwrap(); + + let mut a_to_b_buf = MsgBufPlus::zero(); + let mut b_to_a_buf = MsgBufPlus::zero(); + + let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); + let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); + ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); + + let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); + + let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); + + let init_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); + assert_eq!(init_msg_type, MsgType::InitHello); + + //B handles InitHello, sends RespHello + let HandleMsgResult { resp, .. } = b + .handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf) + .unwrap(); + + let resp_hello_len = resp.unwrap(); + + let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + assert_eq!(resp_msg_type, MsgType::RespHello); + + let HandleMsgResult { + resp, + exchanged_with, + } = a + .handle_msg(&b_to_a_buf[..resp_hello_len], &mut *a_to_b_buf) + .unwrap(); + + let init_conf_len = resp.unwrap(); + let init_conf_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); + + assert_eq!(exchanged_with, Some(PeerPtr(0))); + assert_eq!(init_conf_msg_type, MsgType::InitConf); + + //B handles InitConf, sends EmptyData + let HandleMsgResult { + resp: _, + exchanged_with, + } = b + .handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf) + .unwrap(); + + let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + + assert_eq!(exchanged_with, Some(PeerPtr(0))); + assert_eq!(empty_data_msg_type, MsgType::EmptyData); + }); +} + +#[test] +#[serial] +fn test_regular_init_conf_retransmit_v02() { + test_regular_init_conf_retransmit(ProtocolVersion::V02) +} + +#[test] +#[serial] +fn test_regular_init_conf_retransmit_v03() { + test_regular_init_conf_retransmit(ProtocolVersion::V03) +} + +fn test_regular_init_conf_retransmit(protocol_version: ProtocolVersion) { + setup_logging(); + rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); + stacker::grow(8 * 1024 * 1024, || { + type MsgBufPlus = Public; + let (mut a, mut b) = make_server_pair(protocol_version).unwrap(); + + let mut a_to_b_buf = MsgBufPlus::zero(); + let mut b_to_a_buf = MsgBufPlus::zero(); + + let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); + let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); + ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); + + let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); + + let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); + + let init_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); + assert_eq!(init_msg_type, MsgType::InitHello); + + //B handles InitHello, sends RespHello + let HandleMsgResult { resp, .. } = b + .handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf) + .unwrap(); + + let resp_hello_len = resp.unwrap(); + + let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + assert_eq!(resp_msg_type, MsgType::RespHello); + + //A handles RespHello, sends InitConf, exchanges keys + let HandleMsgResult { + resp, + exchanged_with, + } = a + .handle_msg(&b_to_a_buf[..resp_hello_len], &mut *a_to_b_buf) + .unwrap(); + + let init_conf_len = resp.unwrap(); + let init_conf_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); + + assert_eq!(exchanged_with, Some(PeerPtr(0))); + assert_eq!(init_conf_msg_type, MsgType::InitConf); + + //B handles InitConf, sends EmptyData + let HandleMsgResult { + resp: _, + exchanged_with, + } = b + .handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf) + .unwrap(); + + let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + + assert_eq!(exchanged_with, Some(PeerPtr(0))); + assert_eq!(empty_data_msg_type, MsgType::EmptyData); + + //B handles InitConf again, sends EmptyData + let HandleMsgResult { + resp: _, + exchanged_with, + } = b + .handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf) + .unwrap(); + + let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + + assert!(exchanged_with.is_none()); + assert_eq!(empty_data_msg_type, MsgType::EmptyData); + }); +} + +#[test] +#[serial] +#[cfg(feature = "experiment_cookie_dos_mitigation")] +fn cookie_reply_mechanism_responder_under_load_v02() { + cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V02) +} + +#[test] +#[serial] +#[cfg(feature = "experiment_cookie_dos_mitigation")] +fn cookie_reply_mechanism_responder_under_load_v03() { + cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V03) +} + +#[cfg(feature = "experiment_cookie_dos_mitigation")] +fn cookie_reply_mechanism_responder_under_load(protocol_version: ProtocolVersion) { + use std::{thread::sleep, time::Duration}; + + use super::{Lifecycle, MortalExt}; + + setup_logging(); + rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); + stacker::grow(8 * 1024 * 1024, || { + type MsgBufPlus = Public; + let (mut a, mut b) = make_server_pair(protocol_version.clone()).unwrap(); + + let mut a_to_b_buf = MsgBufPlus::zero(); + let mut b_to_a_buf = MsgBufPlus::zero(); + + let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); + let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); + ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); + + let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); + + let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); + let socket_addr_a = std::net::SocketAddr::V4(ip_a); + let mut ip_addr_port_a = match socket_addr_a.ip() { + std::net::IpAddr::V4(ipv4) => ipv4.octets().to_vec(), + std::net::IpAddr::V6(ipv6) => ipv6.octets().to_vec(), + }; + + ip_addr_port_a.extend_from_slice(&socket_addr_a.port().to_be_bytes()); + + let ip_addr_port_a: VecHostIdentifier = ip_addr_port_a.into(); + + //B handles handshake under load, should send cookie reply message with invalid cookie + let HandleMsgResult { resp, .. } = b + .handle_msg_under_load( + &a_to_b_buf.as_slice()[..init_hello_len], + &mut *b_to_a_buf, + &ip_addr_port_a, + ) + .unwrap(); + + let cookie_reply_len = resp.unwrap(); + + //A handles cookie reply message + a.handle_msg(&b_to_a_buf[..cookie_reply_len], &mut *a_to_b_buf) + .unwrap(); + + assert_eq!(PeerPtr(0).cv().lifecycle(&a), Lifecycle::Young); + + let expected_cookie_value = + crate::hash_domains::cookie_value(protocol_version.keyed_hash()) + .unwrap() + .mix( + b.active_or_retired_cookie_secrets()[0] + .unwrap() + .get(&b) + .value + .secret(), + ) + .unwrap() + .mix(ip_addr_port_a.encode()) + .unwrap() + .into_value()[..16] + .to_vec(); + + assert_eq!( + PeerPtr(0).cv().get(&a).map(|x| &x.value.secret()[..]), + Some(&expected_cookie_value[..]) + ); + + let retx_init_hello_len = loop { + match a.poll().unwrap() { + PollResult::SendRetransmission(peer) => { + break a.retransmit_handshake(peer, &mut *a_to_b_buf).unwrap(); + } + PollResult::Sleep(time) => { + sleep(Duration::from_secs_f64(time)); + } + _ => {} + } + }; + + let retx_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap(); + assert_eq!(retx_msg_type, MsgType::InitHello); + + //B handles retransmitted message + let HandleMsgResult { resp, .. } = b + .handle_msg_under_load( + &a_to_b_buf.as_slice()[..retx_init_hello_len], + &mut *b_to_a_buf, + &ip_addr_port_a, + ) + .unwrap(); + + let _resp_hello_len = resp.unwrap(); + + let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + assert_eq!(resp_msg_type, MsgType::RespHello); + }); +} + +#[test] +#[serial] +#[cfg(feature = "experiment_cookie_dos_mitigation")] +fn cookie_reply_mechanism_initiator_bails_on_message_under_load_v02() { + cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V02) +} + +#[test] +#[serial] +#[cfg(feature = "experiment_cookie_dos_mitigation")] +fn cookie_reply_mechanism_initiator_bails_on_message_under_load_v03() { + cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V03) +} + +#[cfg(feature = "experiment_cookie_dos_mitigation")] +fn cookie_reply_mechanism_initiator_bails_on_message_under_load(protocol_version: ProtocolVersion) { + setup_logging(); + rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); + stacker::grow(8 * 1024 * 1024, || { + type MsgBufPlus = Public; + let (mut a, mut b) = make_server_pair(protocol_version).unwrap(); + + let mut a_to_b_buf = MsgBufPlus::zero(); + let mut b_to_a_buf = MsgBufPlus::zero(); + + let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap(); + let mut ip_addr_port_a = ip_a.ip().octets().to_vec(); + ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes()); + let ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap(); + + //A initiates handshake + let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap(); + + //B handles InitHello message, should respond with RespHello + let HandleMsgResult { resp, .. } = b + .handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf) + .unwrap(); + + let resp_hello_len = resp.unwrap(); + let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap(); + assert_eq!(resp_msg_type, MsgType::RespHello); + + let socket_addr_b = std::net::SocketAddr::V4(ip_b); + let mut ip_addr_port_b = [0u8; 18]; + let mut ip_addr_port_b_len = 0; + match socket_addr_b.ip() { + std::net::IpAddr::V4(ipv4) => { + ip_addr_port_b[0..4].copy_from_slice(&ipv4.octets()); + ip_addr_port_b_len += 4; + } + std::net::IpAddr::V6(ipv6) => { + ip_addr_port_b[0..16].copy_from_slice(&ipv6.octets()); + ip_addr_port_b_len += 16; + } + }; + + ip_addr_port_b[ip_addr_port_b_len..ip_addr_port_b_len + 2] + .copy_from_slice(&socket_addr_b.port().to_be_bytes()); + ip_addr_port_b_len += 2; + + let ip_addr_port_b: VecHostIdentifier = + ip_addr_port_b[..ip_addr_port_b_len].to_vec().into(); + + //A handles RespHello message under load, should not send cookie reply + assert!(a + .handle_msg_under_load( + &b_to_a_buf[..resp_hello_len], + &mut *a_to_b_buf, + &ip_addr_port_b + ) + .is_err()); + }); +} + +#[test] +fn init_conf_retransmission_v02() -> Result<()> { + init_conf_retransmission(ProtocolVersion::V02) +} + +#[test] +fn init_conf_retransmission_v03() -> Result<()> { + init_conf_retransmission(ProtocolVersion::V03) +} + +fn init_conf_retransmission(protocol_version: ProtocolVersion) -> anyhow::Result<()> { + rosenpass_secret_memory::secret_policy_try_use_memfd_secrets(); + + fn keypair() -> Result<(SSk, SPk)> { + let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); + StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?; + Ok((sk, pk)) + } + + fn proc_initiation(srv: &mut CryptoServer, peer: PeerPtr) -> Result> { + let mut buf = MsgBuf::zero(); + srv.initiate_handshake(peer, buf.as_mut_slice())? + .discard_result(); + let msg = truncating_cast_into::>(buf.borrow_mut())?; + Ok(msg.read()) + } + + fn proc_msg( + srv: &mut CryptoServer, + rx: &Envelope, + ) -> anyhow::Result> { + let mut buf = MsgBuf::zero(); + srv.handle_msg(rx.as_bytes(), buf.as_mut_slice())? + .resp + .context("Failed to produce RespHello message")? + .discard_result(); + let msg = truncating_cast_into::>(buf.borrow_mut())?; + Ok(msg.read()) + } + + fn proc_init_hello( + srv: &mut CryptoServer, + ih: &Envelope, + ) -> anyhow::Result> { + proc_msg::(srv, ih) + } + + fn proc_resp_hello( + srv: &mut CryptoServer, + rh: &Envelope, + ) -> anyhow::Result> { + proc_msg::(srv, rh) + } + + fn proc_init_conf( + srv: &mut CryptoServer, + rh: &Envelope, + ) -> anyhow::Result> { + proc_msg::(srv, rh) + } + + fn poll(srv: &mut CryptoServer) -> anyhow::Result<()> { + // Discard all events; just apply the side effects + while !matches!(srv.poll()?, PollResult::Sleep(_)) {} + Ok(()) + } + + // TODO: Implement Clone on our message types + fn clone_msg(msg: &Msg) -> anyhow::Result { + Ok(truncating_cast_into_nomut::(msg.as_bytes())?.read()) + } + + fn break_payload( + srv: &mut CryptoServer, + peer: PeerPtr, + msg: &Envelope, + ) -> anyhow::Result> { + let mut msg = clone_msg(msg)?; + msg.as_bytes_mut()[memoffset::offset_of!(Envelope, payload)] ^= 0x01; + msg.seal(peer, srv)?; // Recalculate seal; we do not want to focus on "seal broken" errs + Ok(msg) + } + + fn check_faulty_proc_init_conf(srv: &mut CryptoServer, ic_broken: &Envelope) { + let mut buf = MsgBuf::zero(); + let res = srv.handle_msg(ic_broken.as_bytes(), buf.as_mut_slice()); + assert!(res.is_err()); + } + + // we this as a closure in orer to use the protocol_version variable in it. + let check_retransmission = |srv: &mut CryptoServer, + ic: &Envelope, + ic_broken: &Envelope, + rc: &Envelope| + -> Result<()> { + // Processing the same RespHello package again leads to retransmission (i.e. exactly the + // same output) + let rc_dup = proc_init_conf(srv, ic)?; + assert_eq!(rc.as_bytes(), rc_dup.as_bytes()); + + // Though if we directly call handle_resp_hello() we get an error since + // retransmission is not being handled by the cryptographic code + let mut discard_resp_conf = EmptyData::new_zeroed(); + let res = srv.handle_init_conf( + &ic.payload, + &mut discard_resp_conf, + protocol_version.clone().keyed_hash(), + ); + assert!(res.is_err()); + + // Obviously, a broken InitConf message should still be rejected + check_faulty_proc_init_conf(srv, ic_broken); + + Ok(()) + }; + + let (ska, pka) = keypair()?; + let (skb, pkb) = keypair()?; + + // initialize server and a pre-shared key + let mut a = CryptoServer::new(ska, pka.clone()); + let mut b = CryptoServer::new(skb, pkb.clone()); + + // introduce peers to each other + let b_peer = a.add_peer( + None, + pkb, + protocol_version.clone(), + OskDomainSeparator::default(), + )?; + let a_peer = b.add_peer( + None, + pka, + protocol_version.clone(), + OskDomainSeparator::default(), + )?; + + // Execute protocol up till the responder confirmation (EmptyData) + let ih1 = proc_initiation(&mut a, b_peer)?; + let rh1 = proc_init_hello(&mut b, &ih1)?; + let ic1 = proc_resp_hello(&mut a, &rh1)?; + let rc1 = proc_init_conf(&mut b, &ic1)?; + + // Modified version of ic1 and rc1, for tests that require it + let ic1_broken = break_payload(&mut a, b_peer, &ic1)?; + assert_ne!(ic1.as_bytes(), ic1_broken.as_bytes()); + + // Modified version of rc1, for tests that require it + let rc1_broken = break_payload(&mut b, a_peer, &rc1)?; + assert_ne!(rc1.as_bytes(), rc1_broken.as_bytes()); + + // Retransmission works as designed + check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; + + // Even with a couple of poll operations in between (which clears the cache + // after a time out of two minutes…we should never hit this time out in this + // cache) + for _ in 0..4 { + poll(&mut b)?; + check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; + } + // We can even validate that the data is coming out of the cache by changing the cache + // to use our broken messages. It does not matter that these messages are cryptographically + // broken since we insert them manually into the cache + // a_peer.known_init_conf_response() + KnownInitConfResponsePtr::insert_for_request_msg( + &mut b, + a_peer, + &ic1_broken, + rc1_broken.clone(), + ); + check_retransmission(&mut b, &ic1_broken, &ic1, &rc1_broken)?; + + // Lets reset to the correct message though + KnownInitConfResponsePtr::insert_for_request_msg(&mut b, a_peer, &ic1, rc1.clone()); + + // Again, nothing changes after calling poll + poll(&mut b)?; + check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; + + // Except if we jump forward into the future past the point where the responder + // starts to initiate rekeying; in this case, the automatic time out is triggered and the cache is cleared + super::testutils::time_travel_forward(&mut b, REKEY_AFTER_TIME_RESPONDER); + + // As long as we do not call poll, everything is fine + check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?; + + // But after we do, the response is gone and can not be recreated + // since the biscuit is stale + poll(&mut b)?; + check_faulty_proc_init_conf(&mut b, &ic1); // ic1 is now effectively broken + assert!(b.peers[0].known_init_conf_response.is_none()); // The cache is gone + + Ok(()) +} diff --git a/rosenpass/src/protocol/testutils.rs b/rosenpass/src/protocol/testutils.rs new file mode 100644 index 00000000..8ba51832 --- /dev/null +++ b/rosenpass/src/protocol/testutils.rs @@ -0,0 +1,54 @@ +//! Helpers used in tests + +use std::ops::DerefMut; + +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; + +use super::{ + basic_types::{SPk, SSk}, + osk_domain_separator::OskDomainSeparator, + CryptoServer, PeerPtr, ProtocolVersion, +}; + +/// Helper for tests and examples +pub struct ServerForTesting { + pub peer: PeerPtr, + pub peer_keys: (SSk, SPk), + pub srv: CryptoServer, +} + +/// TODO: Document that the protocol version is only used for creating the peer for testing +impl ServerForTesting { + pub fn new(protocol_version: ProtocolVersion) -> anyhow::Result { + let (mut sskm, mut spkm) = (SSk::zero(), SPk::zero()); + StaticKem.keygen(sskm.secret_mut(), spkm.deref_mut())?; + let mut srv = CryptoServer::new(sskm, spkm); + + let (mut sskt, mut spkt) = (SSk::zero(), SPk::zero()); + StaticKem.keygen(sskt.secret_mut(), spkt.deref_mut())?; + let peer = srv.add_peer( + None, + spkt.clone(), + protocol_version, + OskDomainSeparator::default(), + )?; + + let peer_keys = (sskt, spkt); + Ok(ServerForTesting { + peer, + peer_keys, + srv, + }) + } + + pub fn tuple(self) -> (PeerPtr, (SSk, SPk), CryptoServer) { + (self.peer, self.peer_keys, self.srv) + } +} + +/// Time travel forward in time +pub fn time_travel_forward(srv: &mut CryptoServer, secs: f64) { + let dur = std::time::Duration::from_secs_f64(secs); + srv.timebase.0 = srv.timebase.0.checked_sub(dur).unwrap(); +} diff --git a/rosenpass/src/protocol/timing.rs b/rosenpass/src/protocol/timing.rs new file mode 100644 index 00000000..3e34011a --- /dev/null +++ b/rosenpass/src/protocol/timing.rs @@ -0,0 +1,46 @@ +//! Time-keeping related utilities for the Rosenpass protocol + +use super::constants::EVENT_GRACE; + +/// A type for time, e.g. for backoff before re-tries +pub type Timing = f64; + +/// Magic time stamp to indicate some object is ancient; "Before Common Era" +/// +/// This is for instance used as a magic time stamp indicating age when some +/// cryptographic object certainly needs to be refreshed. +/// +/// Using this instead of Timing::MIN or Timing::INFINITY to avoid floating +/// point math weirdness. +pub const BCE: Timing = -3600.0 * 24.0 * 356.0 * 10_000.0; + +/// Magic time stamp to indicate that some process is not time-limited +/// +/// Actually it's eight hours; This is intentional to avoid weirdness +/// regarding unexpectedly large numbers in system APIs as this is < i16::MAX +pub const UNENDING: Timing = 3600.0 * 8.0; + +/// An even `ev` has happened relative to a point in time `now` +/// if the `ev` does not lie in the future relative to now. +/// +/// An event lies in the future relative to `now` if +/// does not lie in the past or present. +/// +/// An event `ev` lies in the past if `ev < now`. It lies in the +/// present if the absolute difference between `ev` and `now` is +/// smaller than [EVENT_GRACE]. +/// +/// Think of this as `ev <= now` for with [EVENT_GRACE] applied. +/// +/// # Examples +/// +/// ``` +/// use rosenpass::protocol::{timing::has_happened, constants::EVENT_GRACE}; +/// assert!(has_happened(EVENT_GRACE * -1.0, 0.0)); +/// assert!(has_happened(0.0, 0.0)); +/// assert!(has_happened(EVENT_GRACE * 0.999, 0.0)); +/// assert!(!has_happened(EVENT_GRACE * 1.001, 0.0)); +/// ``` +pub fn has_happened(ev: Timing, now: Timing) -> bool { + (ev - now) < EVENT_GRACE +} diff --git a/rosenpass/src/protocol/zerocopy.rs b/rosenpass/src/protocol/zerocopy.rs new file mode 100644 index 00000000..3e8639b6 --- /dev/null +++ b/rosenpass/src/protocol/zerocopy.rs @@ -0,0 +1,21 @@ +//! Helpers for working with the zerocopy crate + +use std::mem::size_of; + +use zerocopy::{FromBytes, Ref}; + +use crate::RosenpassError; + +/// Used to parse a network message using [zerocopy] +pub fn truncating_cast_into( + buf: &mut [u8], +) -> Result, RosenpassError> { + Ref::new(&mut buf[..size_of::()]).ok_or(RosenpassError::BufferSizeMismatch) +} + +/// Used to parse a network message using [zerocopy], mutably +pub fn truncating_cast_into_nomut( + buf: &[u8], +) -> Result, RosenpassError> { + Ref::new(&buf[..size_of::()]).ok_or(RosenpassError::BufferSizeMismatch) +} diff --git a/rosenpass/tests/api-integration-tests-api-setup.rs b/rosenpass/tests/api-integration-tests-api-setup.rs index bb5ff8c4..ee9341a2 100644 --- a/rosenpass/tests/api-integration-tests-api-setup.rs +++ b/rosenpass/tests/api-integration-tests-api-setup.rs @@ -14,6 +14,8 @@ use rosenpass::api::{ self, add_listen_socket_response_status, add_psk_broker_response_status, supply_keypair_response_status, }; +use rosenpass::config::ProtocolVersion; +use rosenpass::protocol::basic_types::SymKey; use rosenpass_util::{ b64::B64Display, file::LoadValueB64, @@ -27,8 +29,6 @@ use std::os::fd::{AsFd, AsRawFd}; use tempfile::TempDir; use zerocopy::AsBytes; -use rosenpass::protocol::SymKey; - struct KillChild(std::process::Child); impl Drop for KillChild { @@ -48,7 +48,16 @@ impl Drop for KillChild { } #[test] -fn api_integration_api_setup() -> anyhow::Result<()> { +fn api_integration_api_setup_v02() -> anyhow::Result<()> { + api_integration_api_setup(ProtocolVersion::V02) +} + +#[test] +fn api_integration_api_setup_v03() -> anyhow::Result<()> { + api_integration_api_setup(ProtocolVersion::V03) +} + +fn api_integration_api_setup(protocol_version: ProtocolVersion) -> anyhow::Result<()> { rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets(); let dir = TempDir::with_prefix("rosenpass-api-integration-test")?; @@ -96,6 +105,8 @@ fn api_integration_api_setup() -> anyhow::Result<()> { peer: format!("{}", peer_b_wg_peer_id.fmt_b64::<8129>()), extra_params: vec![], }), + protocol_version: protocol_version.clone(), + osk_domain_separator: Default::default(), }], }; @@ -116,6 +127,8 @@ fn api_integration_api_setup() -> anyhow::Result<()> { endpoint: Some(peer_a_endpoint.to_owned()), pre_shared_key: None, wg: None, + protocol_version: protocol_version.clone(), + osk_domain_separator: Default::default(), }], }; diff --git a/rosenpass/tests/api-integration-tests.rs b/rosenpass/tests/api-integration-tests.rs index e7e02594..18380c27 100644 --- a/rosenpass/tests/api-integration-tests.rs +++ b/rosenpass/tests/api-integration-tests.rs @@ -16,7 +16,8 @@ use rosenpass_util::{mem::DiscardResultExt, zerocopy::ZerocopySliceExt}; use tempfile::TempDir; use zerocopy::AsBytes; -use rosenpass::protocol::SymKey; +use rosenpass::config::ProtocolVersion; +use rosenpass::protocol::basic_types::SymKey; struct KillChild(std::process::Child); @@ -37,7 +38,15 @@ impl Drop for KillChild { } #[test] -fn api_integration_test() -> anyhow::Result<()> { +fn api_integration_test_v02() -> anyhow::Result<()> { + api_integration_test(ProtocolVersion::V02) +} + +fn api_integration_test_v03() -> anyhow::Result<()> { + api_integration_test(ProtocolVersion::V03) +} + +fn api_integration_test(protocol_version: ProtocolVersion) -> anyhow::Result<()> { rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets(); let dir = TempDir::with_prefix("rosenpass-api-integration-test")?; @@ -73,6 +82,8 @@ fn api_integration_test() -> anyhow::Result<()> { endpoint: None, pre_shared_key: None, wg: None, + protocol_version: protocol_version.clone(), + osk_domain_separator: Default::default(), }], }; @@ -93,6 +104,8 @@ fn api_integration_test() -> anyhow::Result<()> { endpoint: Some(peer_a_endpoint.to_owned()), pre_shared_key: None, wg: None, + protocol_version: protocol_version.clone(), + osk_domain_separator: Default::default(), }], }; diff --git a/rosenpass/tests/app_server_example.rs b/rosenpass/tests/app_server_example.rs index 23ac4625..4b8169a4 100644 --- a/rosenpass/tests/app_server_example.rs +++ b/rosenpass/tests/app_server_example.rs @@ -1,25 +1,25 @@ -use std::{ - net::SocketAddr, - ops::DerefMut, - path::PathBuf, - str::FromStr, - sync::mpsc, - thread::{self, sleep}, - time::Duration, -}; +use std::thread::{self, sleep}; +use std::{net::SocketAddr, ops::DerefMut, str::FromStr, sync::mpsc, time::Duration}; -use anyhow::ensure; -use rosenpass::{ - app_server::{ipv4_any_binding, ipv6_any_binding, AppServer, AppServerTest, MAX_B64_KEY_SIZE}, - protocol::{SPk, SSk, SymKey}, -}; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; -use rosenpass_secret_memory::Secret; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; use rosenpass_util::{file::LoadValueB64, functional::run, mem::DiscardResultExt, result::OkExt}; +use rosenpass::app_server::{AppServer, AppServerTest, MAX_B64_KEY_SIZE}; +use rosenpass::protocol::basic_types::{SPk, SSk, SymKey}; +use rosenpass::{config::ProtocolVersion, protocol::osk_domain_separator::OskDomainSeparator}; + #[test] -fn key_exchange_with_app_server() -> anyhow::Result<()> { +fn key_exchange_with_app_server_v02() -> anyhow::Result<()> { + key_exchange_with_app_server(ProtocolVersion::V02) +} + +#[test] +fn key_exchange_with_app_server_v03() -> anyhow::Result<()> { + key_exchange_with_app_server(ProtocolVersion::V03) +} + +fn key_exchange_with_app_server(protocol_version: ProtocolVersion) -> anyhow::Result<()> { let tmpdir = tempfile::tempdir()?; let outfile_a = tmpdir.path().join("osk_a"); let outfile_b = tmpdir.path().join("osk_b"); @@ -56,8 +56,15 @@ fn key_exchange_with_app_server() -> anyhow::Result<()> { let outfile = Some(osk); let port = otr_port; let hostname = is_client.then(|| format!("[::1]:{port}")); - srv.app_srv - .add_peer(psk, pk, outfile, broker_peer, hostname)?; + srv.app_srv.add_peer( + psk, + pk, + outfile, + broker_peer, + hostname, + protocol_version, + OskDomainSeparator::default(), + )?; srv.app_srv.event_loop() }) @@ -101,7 +108,7 @@ struct TestServer { impl TestServer { fn new(termination_queue: mpsc::Receiver<()>) -> anyhow::Result { let (mut sk, mut pk) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(sk.secret_mut(), pk.deref_mut())?; + StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?; let keypair = Some((sk, pk)); let addrs = vec![ diff --git a/rosenpass/tests/gen-ipc-msg-types.rs b/rosenpass/tests/gen-ipc-msg-types.rs index 3d4629e2..68abaeed 100644 --- a/rosenpass/tests/gen-ipc-msg-types.rs +++ b/rosenpass/tests/gen-ipc-msg-types.rs @@ -1,4 +1,4 @@ -use std::{borrow::Borrow, process::Command}; +use std::process::Command; #[test] fn test_gen_ipc_msg_types() -> anyhow::Result<()> { @@ -9,7 +9,11 @@ fn test_gen_ipc_msg_types() -> anyhow::Result<()> { // Smoke tests only assert!(stdout.contains("type RawMsgType = u128;")); + // For Blake2b: assert!(stdout.contains("const SUPPLY_KEYPAIR_RESPONSE : RawMsgType = RawMsgType::from_le_bytes(hex!(\"f2dc 49bd e261 5f10 40b7 3c16 ec61 edb9\"));")); + // For SHAKE256: + assert!(stdout.contains("const SUPPLY_KEYPAIR_RESPONSE : RawMsgType = RawMsgType::from_le_bytes(hex!(\"ff80 3886 68a4 47ce 2ae6 0915 0972 682f\"))")); + // TODO: Also test SHAKE256 here Ok(()) } diff --git a/rosenpass/tests/integration_test.rs b/rosenpass/tests/integration_test.rs index 67ddc78e..d5b5f22a 100644 --- a/rosenpass/tests/integration_test.rs +++ b/rosenpass/tests/integration_test.rs @@ -129,7 +129,7 @@ fn run_server_client_exchange( }); // give them some time to do the key exchange under load - std::thread::sleep(Duration::from_secs(10)); + std::thread::sleep(Duration::from_secs(30)); // time's up, kill the childs server_terminate.send(()).unwrap(); @@ -251,7 +251,7 @@ fn check_exchange_under_normal() { fs::remove_dir_all(&tmpdir).unwrap(); } -// check that we can trigger a DoS condition and we can exchange keys under DoS +// check that we can trigger a DoS condition, and we can exchange keys under DoS // This test creates a responder (server) with the feature flag "integration_test_always_under_load" to always be under load condition for the test. #[test] #[serial] diff --git a/rosenpass/tests/main-fn-generates-manpages.rs b/rosenpass/tests/main-fn-generates-manpages.rs index 41124c95..30dfdb79 100644 --- a/rosenpass/tests/main-fn-generates-manpages.rs +++ b/rosenpass/tests/main-fn-generates-manpages.rs @@ -46,7 +46,6 @@ fn main_fn_generates_manpages() -> anyhow::Result<()> { "rosenpass-exchange-config.1", "rosenpass-gen-config.1", "rosenpass-gen-keys.1", - "rosenpass-keygen.1", "rosenpass-validate.1", ]; @@ -56,7 +55,10 @@ fn main_fn_generates_manpages() -> anyhow::Result<()> { .map(|name| (name, dir.path().join(name))) .map(|(name, path)| { let res = std::process::Command::new("man").arg(path).output()?; - assert!(res.status.success()); + assert!( + res.status.success(), + "Error rendering manpage {name} using man" + ); let body = res .stdout .apply(String::from_utf8)? @@ -64,7 +66,6 @@ fn main_fn_generates_manpages() -> anyhow::Result<()> { Ok((name, body)) }) .collect::>()?; - for (name, body) in man_texts.iter() { expect_sections(body, &["NAME", "SYNOPSIS", "OPTIONS"])?; diff --git a/rosenpass/tests/poll_example.rs b/rosenpass/tests/poll_example.rs index 56faf792..10cc8757 100644 --- a/rosenpass/tests/poll_example.rs +++ b/rosenpass/tests/poll_example.rs @@ -5,24 +5,53 @@ use std::{ ops::DerefMut, }; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; use rosenpass_util::result::OkExt; -use rosenpass::protocol::{ - testutils::time_travel_forward, CryptoServer, HostIdentification, MsgBuf, PeerPtr, PollResult, - SPk, SSk, SymKey, Timing, UNENDING, -}; +use rosenpass::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey}; +use rosenpass::protocol::osk_domain_separator::OskDomainSeparator; +use rosenpass::protocol::testutils::time_travel_forward; +use rosenpass::protocol::timing::{Timing, UNENDING}; +use rosenpass::protocol::{CryptoServer, HostIdentification, PeerPtr, PollResult, ProtocolVersion}; // TODO: Most of the utility functions in here should probably be moved to // rosenpass::protocol::testutils; #[test] -fn test_successful_exchange_with_poll() -> anyhow::Result<()> { +fn test_successful_exchange_with_poll_v02() -> anyhow::Result<()> { + test_successful_exchange_with_poll(ProtocolVersion::V02, OskDomainSeparator::default()) +} + +#[test] +fn test_successful_exchange_with_poll_v03() -> anyhow::Result<()> { + test_successful_exchange_with_poll(ProtocolVersion::V03, OskDomainSeparator::default()) +} + +#[test] +fn test_successful_exchange_with_poll_v02_custom_domain_separator() -> anyhow::Result<()> { + test_successful_exchange_with_poll( + ProtocolVersion::V02, + OskDomainSeparator::custom_utf8_single_label("example.org", "Example Label"), + ) +} + +#[test] +fn test_successful_exchange_with_poll_v03_custom_domain_separator() -> anyhow::Result<()> { + test_successful_exchange_with_poll( + ProtocolVersion::V03, + OskDomainSeparator::custom_utf8_single_label("example.org", "Example Label"), + ) +} + +fn test_successful_exchange_with_poll( + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, +) -> anyhow::Result<()> { // Set security policy for storing secrets; choose the one that is faster for testing rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets(); - let mut sim = RosenpassSimulator::new()?; + let mut sim = RosenpassSimulator::new(protocol_version, osk_domain_separator)?; sim.poll_loop(150)?; // Poll 75 times let transcript = sim.transcript; @@ -42,9 +71,9 @@ fn test_successful_exchange_with_poll() -> anyhow::Result<()> { ); #[cfg(not(coverage))] assert!( - _completions[0].0 < 20.0, + _completions[0].0 < 60.0, "\ - First key exchange should happen in under twenty seconds!\n\ + First key exchange should happen in under 60 seconds!\n\ Transcript: {transcript:?}\n\ Completions: {_completions:?}\ " @@ -79,12 +108,23 @@ fn test_successful_exchange_with_poll() -> anyhow::Result<()> { } #[test] -fn test_successful_exchange_under_packet_loss() -> anyhow::Result<()> { +fn test_successful_exchange_under_packet_loss_v02() -> anyhow::Result<()> { + test_successful_exchange_under_packet_loss(ProtocolVersion::V02) +} + +#[test] +fn test_successful_exchange_under_packet_loss_v03() -> anyhow::Result<()> { + test_successful_exchange_under_packet_loss(ProtocolVersion::V03) +} + +fn test_successful_exchange_under_packet_loss( + protocol_version: ProtocolVersion, +) -> anyhow::Result<()> { // Set security policy for storing secrets; choose the one that is faster for testing rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets(); // Create the simulator - let mut sim = RosenpassSimulator::new()?; + let mut sim = RosenpassSimulator::new(protocol_version, OskDomainSeparator::default())?; // Make sure the servers are set to under load condition sim.srv_a.under_load = true; @@ -99,7 +139,7 @@ fn test_successful_exchange_under_packet_loss() -> anyhow::Result<()> { event: ServerEvent::Transmit(_, _), } = ev { - // Drop every fifth package + // Drop every tenth package if pkg_counter % 10 == 0 { source.drop_outgoing_packet(&mut sim); } @@ -125,9 +165,9 @@ fn test_successful_exchange_under_packet_loss() -> anyhow::Result<()> { ); #[cfg(not(coverage))] assert!( - _completions[0].0 < 10.0, + _completions[0].0 < 60.0, "\ - First key exchange should happen in under twenty seconds!\n\ + First key exchange should happen in under 60 seconds!\n\ Transcript: {transcript:?}\n\ Completions: {_completions:?}\ " @@ -161,6 +201,94 @@ fn test_successful_exchange_under_packet_loss() -> anyhow::Result<()> { Ok(()) } +#[test] +fn test_osk_label_mismatch() -> anyhow::Result<()> { + // Set security policy for storing secrets; choose the one that is faster for testing + rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets(); + + let ds_wg = OskDomainSeparator::for_wireguard_psk(); + let ds_custom1 = OskDomainSeparator::custom_utf8("example.com", ["Example Label"]); + let ds_custom2 = + OskDomainSeparator::custom_utf8("example.com", ["Example Label", "Second Token"]); + + // Create the simulator + let mut sim = RosenpassSimulator::new(ProtocolVersion::V03, ds_custom1.clone())?; + assert_eq!(sim.srv_a.srv.peers[0].osk_domain_separator, ds_custom1); + assert_eq!(sim.srv_b.srv.peers[0].osk_domain_separator, ds_custom1); + + // Deliberately produce a label mismatch + sim.srv_b.srv.peers[0].osk_domain_separator = ds_custom2.clone(); + assert_eq!(sim.srv_a.srv.peers[0].osk_domain_separator, ds_custom1); + assert_eq!(sim.srv_b.srv.peers[0].osk_domain_separator, ds_custom2); + + // Perform the key exchanges + for _ in 0..300 { + let ev = sim.poll()?; + + assert!(!matches!(ev, TranscriptEvent::CompletedExchange(_)), + "We deliberately provoked a mismatch in OSK domain separator, but still saw a successfully completed key exchange"); + + // Wait for a key exchange that failed with a KeyMismatch event + let (osk_a_custom1, osk_b_custom2) = match ev { + TranscriptEvent::FailedExchangeWithKeyMismatch(osk_a, osk_b) => { + (osk_a.clone(), osk_b.clone()) + } + _ => continue, + }; + + // The OSKs have been produced through the call to the function CryptoServer::osk(…) + assert_eq!( + sim.srv_a.srv.osk(PeerPtr(0))?.secret(), + osk_a_custom1.secret() + ); + assert_eq!( + sim.srv_b.srv.osk(PeerPtr(0))?.secret(), + osk_b_custom2.secret() + ); + + // They are not matching (obviously) + assert_ne!(osk_a_custom1.secret(), osk_b_custom2.secret()); + + // We can manually generate OSKs with matching labels + let osk_a_custom2 = sim + .srv_a + .srv + .osk_with_domain_separator(PeerPtr(0), &ds_custom2)?; + let osk_b_custom1 = sim + .srv_b + .srv + .osk_with_domain_separator(PeerPtr(0), &ds_custom1)?; + let osk_a_wg = sim + .srv_a + .srv + .osk_with_domain_separator(PeerPtr(0), &ds_wg)?; + let osk_b_wg = sim + .srv_b + .srv + .osk_with_domain_separator(PeerPtr(0), &ds_wg)?; + + // The key exchange may have failed for some other reason, in this case we expect a + // successful-but-label-mismatch exchange later in the protocol + if osk_a_custom1.secret() != osk_b_custom1.secret() { + continue; + } + + // But if one of the labeled keys match, all should match + assert_eq!(osk_a_custom2.secret(), osk_b_custom2.secret()); + assert_eq!(osk_a_wg.secret(), osk_b_wg.secret()); + + // But the three keys do not match each other + assert_ne!(osk_a_custom1.secret(), osk_a_custom2.secret()); + assert_ne!(osk_a_custom1.secret(), osk_a_wg.secret()); + assert_ne!(osk_a_custom2.secret(), osk_a_wg.secret()); + + // The test succeeded + return Ok(()); + } + + panic!("Test did not succeed even after allowing for a large number of communication rounds"); +} + type MessageType = u8; /// Lets record the events that are produced by Rosenpass @@ -173,6 +301,7 @@ enum TranscriptEvent { event: ServerEvent, }, CompletedExchange(SymKey), + FailedExchangeWithKeyMismatch(SymKey, SymKey), } #[derive(Debug)] @@ -272,21 +401,34 @@ struct SimulatorServer { impl RosenpassSimulator { /// Set up the simulator - fn new() -> anyhow::Result { + fn new( + protocol_version: ProtocolVersion, + osk_domain_separator: OskDomainSeparator, + ) -> anyhow::Result { // Set up the first server let (mut peer_a_sk, mut peer_a_pk) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(peer_a_sk.secret_mut(), peer_a_pk.deref_mut())?; + StaticKem.keygen(peer_a_sk.secret_mut(), peer_a_pk.deref_mut())?; let mut srv_a = CryptoServer::new(peer_a_sk, peer_a_pk.clone()); // …and the second server. let (mut peer_b_sk, mut peer_b_pk) = (SSk::zero(), SPk::zero()); - StaticKem::keygen(peer_b_sk.secret_mut(), peer_b_pk.deref_mut())?; + StaticKem.keygen(peer_b_sk.secret_mut(), peer_b_pk.deref_mut())?; let mut srv_b = CryptoServer::new(peer_b_sk, peer_b_pk.clone()); // Generate a PSK and introduce the Peers to each other. let psk = SymKey::random(); - let peer_a = srv_a.add_peer(Some(psk.clone()), peer_b_pk)?; - let peer_b = srv_b.add_peer(Some(psk), peer_a_pk)?; + let peer_a = srv_a.add_peer( + Some(psk.clone()), + peer_b_pk, + protocol_version.clone(), + osk_domain_separator.clone(), + )?; + let peer_b = srv_b.add_peer( + Some(psk), + peer_a_pk, + protocol_version.clone(), + osk_domain_separator.clone(), + )?; // Set up the individual server data structures let srv_a = SimulatorServer::new(srv_a, peer_b); @@ -314,8 +456,8 @@ impl RosenpassSimulator { Ok(()) } - /// Every call to poll produces one [TranscriptEvent] and - /// and implicitly adds it to [Self:::transcript] + /// Every call to poll produces one [TranscriptEvent] + /// and implicitly adds it to [Self::transcript] fn poll(&mut self) -> anyhow::Result<&TranscriptEvent> { let ev = TranscriptEvent::begin_poll() .try_fold_with(|| self.poll_focus.poll(self))? @@ -490,8 +632,11 @@ impl ServerPtr { // Let the crypto server handle the message now let mut tx_buf = MsgBuf::zero(); let handle_msg_result = if self.get(sim).under_load { - self.srv_mut(sim) - .handle_msg_under_load(rx_msg.borrow(), tx_buf.borrow_mut(), &self) + self.srv_mut(sim).handle_msg_under_load( + rx_msg.borrow(), + tx_buf.borrow_mut(), + &self.other(), + ) } else { self.srv_mut(sim) .handle_msg(rx_msg.borrow(), tx_buf.borrow_mut()) @@ -543,10 +688,18 @@ impl ServerPtr { None => return Ok(()), }; + // Make sure the OSK of server A always comes first + let (osk_a, osk_b) = match self == ServerPtr::A { + true => (osk, other_osk), + false => (other_osk, osk), + }; + // Issue the successful exchange event if the OSKs are equal; // be careful to use constant time comparison for things like this! - if rosenpass_constant_time::memcmp(osk.secret(), other_osk.secret()) { - self.enqueue_upcoming_poll_event(sim, TE::CompletedExchange(osk)); + if rosenpass_constant_time::memcmp(osk_a.secret(), osk_b.secret()) { + self.enqueue_upcoming_poll_event(sim, TE::CompletedExchange(osk_a)); + } else { + self.enqueue_upcoming_poll_event(sim, TE::FailedExchangeWithKeyMismatch(osk_a, osk_b)); } Ok(()) diff --git a/rp/Cargo.toml b/rp/Cargo.toml index 22a8e90a..5b3091f3 100644 --- a/rp/Cargo.toml +++ b/rp/Cargo.toml @@ -6,6 +6,7 @@ license = "MIT OR Apache-2.0" description = "Build post-quantum-secure VPNs with WireGuard!" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" +rust-version = "1.77.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -14,7 +15,7 @@ anyhow = { workspace = true } base64ct = { workspace = true } serde = { workspace = true } toml = { workspace = true } -x25519-dalek = { version = "2", features = ["static_secrets"] } +x25519-dalek = { workspace = true, features = ["static_secrets"] } zeroize = { workspace = true } rosenpass = { workspace = true } @@ -26,8 +27,8 @@ rosenpass-wireguard-broker = { workspace = true } tokio = { workspace = true } -futures = "0.3" -futures-util = "0.3" +futures = { workspace = true } +futures-util = { workspace = true } [target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies] ctrlc-async = "3.2" @@ -43,4 +44,4 @@ stacker = { workspace = true } [features] experiment_memfd_secret = [] -experiment_libcrux = ["rosenpass-ciphers/experiment_libcrux"] +experiment_libcrux = ["rosenpass-ciphers/experiment_libcrux_all"] diff --git a/rp/src/exchange.rs b/rp/src/exchange.rs index 6deb9ba0..d3f729cd 100644 --- a/rp/src/exchange.rs +++ b/rp/src/exchange.rs @@ -1,12 +1,12 @@ -use anyhow::Error; -use serde::Deserialize; -use std::future::Future; -use std::ops::DerefMut; -use std::pin::Pin; -use std::sync::Arc; -use std::{net::SocketAddr, path::PathBuf, process::Command}; +use std::{ + future::Future, net::SocketAddr, ops::DerefMut, path::PathBuf, pin::Pin, process::Command, + sync::Arc, +}; -use anyhow::Result; +use anyhow::{Error, Result}; +use serde::Deserialize; + +use rosenpass::config::ProtocolVersion; #[cfg(any(target_os = "linux", target_os = "freebsd"))] use crate::key::WG_B64_LEN; @@ -15,6 +15,7 @@ use crate::key::WG_B64_LEN; /// a directory for storing public keys and optionally an IP address and port of the endpoint, /// for how long the connection should be kept alive and a list of allowed IPs for the peer. #[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] pub struct ExchangePeer { /// Directory where public keys are stored pub public_keys_dir: PathBuf, @@ -24,10 +25,14 @@ pub struct ExchangePeer { pub persistent_keepalive: Option, /// The IPs that are allowed for this peer. pub allowed_ips: Option, + /// The protocol version used by the peer. + #[serde(default)] + pub protocol_version: ProtocolVersion, } /// Options for the exchange operation of the `rp` binary. #[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] pub struct ExchangeOptions { /// Whether the cli output should be verbose. pub verbose: bool, @@ -203,7 +208,10 @@ pub async fn exchange(options: ExchangeOptions) -> Result<()> { use rosenpass::{ app_server::{AppServer, BrokerPeer}, config::Verbosity, - protocol::{SPk, SSk, SymKey}, + protocol::{ + basic_types::{SPk, SSk, SymKey}, + osk_domain_separator::OskDomainSeparator, + }, }; use rosenpass_secret_memory::Secret; use rosenpass_util::file::{LoadValue as _, LoadValueB64}; @@ -356,6 +364,8 @@ pub async fn exchange(options: ExchangeOptions) -> Result<()> { None, broker_peer, peer.endpoint.map(|x| x.to_string()), + peer.protocol_version, + OskDomainSeparator::for_wireguard_psk(), )?; // Configure routes, equivalent to `ip route replace dev ` and set up diff --git a/rp/src/key.rs b/rp/src/key.rs index f061d058..f6089e7e 100644 --- a/rp/src/key.rs +++ b/rp/src/key.rs @@ -9,9 +9,9 @@ use anyhow::{anyhow, Result}; use rosenpass_util::file::{LoadValueB64, StoreValue, StoreValueB64}; use zeroize::Zeroize; -use rosenpass::protocol::{SPk, SSk}; -use rosenpass_cipher_traits::Kem; -use rosenpass_ciphers::kem::StaticKem; +use rosenpass::protocol::basic_types::{SPk, SSk}; +use rosenpass_cipher_traits::primitives::Kem; +use rosenpass_ciphers::StaticKem; use rosenpass_secret_memory::{file::StoreSecret as _, Public, Secret}; /// The length of wireguard keys as a length in base 64 encoding. @@ -66,7 +66,7 @@ pub fn genkey(private_keys_dir: &Path) -> Result<()> { if !pqsk_path.exists() && !pqpk_path.exists() { let mut pqsk = SSk::random(); let mut pqpk = SPk::random(); - StaticKem::keygen(pqsk.secret_mut(), pqpk.deref_mut())?; + StaticKem.keygen(pqsk.secret_mut(), pqpk.deref_mut())?; pqpk.store(pqpk_path)?; pqsk.store_secret(pqsk_path)?; } else { @@ -118,7 +118,7 @@ pub fn pubkey(private_keys_dir: &Path, public_keys_dir: &Path) -> Result<()> { mod tests { use std::fs; - use rosenpass::protocol::{SPk, SSk}; + use rosenpass::protocol::basic_types::{SPk, SSk}; use rosenpass_secret_memory::secret_policy_try_use_memfd_secrets; use rosenpass_secret_memory::Secret; use rosenpass_util::file::LoadValue; diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..83025f97 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "1.77.0" diff --git a/secret-memory/Cargo.toml b/secret-memory/Cargo.toml index e186ec70..50f5881f 100644 --- a/secret-memory/Cargo.toml +++ b/secret-memory/Cargo.toml @@ -8,6 +8,7 @@ description = "Rosenpass internal utilities for storing secrets in memory" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [dependencies] anyhow = { workspace = true } diff --git a/supply-chain-CI.md b/supply-chain-CI.md new file mode 100644 index 00000000..8e883596 --- /dev/null +++ b/supply-chain-CI.md @@ -0,0 +1,25 @@ +# Continuous Integration for supply chain protection + +This repository's CI uses non-standard mechanisms to harmonize the usage of `dependabot` together with [`cargo vet`](https://mozilla.github.io/cargo-vet/). Since cargo-vet audits for new versions of crates are rarely immediately available once dependabots bumps the version, +the exemptions for `cargo vet` have to be regenerated for each push request opened by dependabot. To make this work, some setup is neccessary to setup the CI. The required steps are as follows: + +1. Create a mew user on github. For the purpose of these instructions, we will assume that its mail address is `ci@example.com` and that its username is `ci-bot`. Protect this user account as you would any other user account that you intend to gve write permissions to. For example, setup MFA or protect the email address of the user. Make sure to verify your e-mail. +2. Add `ci-bot` as a member of your organizaton with write access to the repository. +3. In your organization, go to "Settings" -> "Personal Access tokens" -> "Settings". There select "Allow access via fine-grained personal access tokens" and save. Depending on your preferences either choose "Require administrator approval" or "Do not require administrator approval". +4. Create a new personal access token as `ci-bot` for the rosenpass repository. That is, in the settings for `ci-bot`, select "Developer settings" -> "Personal Access tokens" -> "Fine-grained tokens". Then click on "Generate new token". Enter a name of your choosing and choose an expiration date that you feel comfortable with. A shorter expiration period will requrie more manual management by you but is more secure than a longer one. Select your organization as the resource owner and select the rosenpass repository as the repository. Under "Repository permissions", grant "Read and write"-access to the "Contens" premission for the token. Grant no other permissions to the token, except for the read-only access to the "Metadata" permission, which is mandatory. Then generate the token and copy it for the next steps. +5. If you chose "Require administrator approval" in step 3, approve the fine grained access token by, as a organization administrator, going to "Settings" -> "Personal Access tokens" -> "Pending requests" and grant the request. +6. Now, with your account that has administrative permissions for the repository, open the settings page for the repository and select "Secrets and variables" -> "Actions" and click "New repository secret". In the name field enter "CI_BOT_PAT". This name is mandatory, since it is explicitly referenced in the supply-chain workflow. Below, enter the token that was generated in step 4. +7. Analogously to step 6, open the settings page for the repository and select "Secrets and variables" -> "Dependabot" and click "New repository secret". In the name field enter "CI_BOT_PAT". This name is mandatory, since it is explicitly referenced in the supply-chain workflow. Below, enter the token that was generated in step 4. + +## What this does + +For the `cargo vet` check in the CI for dependabot, the `cargo vet`-exemptions have to automatically be regenerated, because otherwise this CI job will always fail for dependabot PRs. After the exemptions have been regenerated, they need to be commited and pushed to the PR. This invalidates the CI run that pushed the commit so that it does not show up in the PR anymore but does not trigger a new CI run. This is a [protection by Github](https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#using-the-github_token-in-a-workflow) to prevent infinite loops. However, in this case it prevents us from having a proper CI run for dependabot PRs. The solution to this is to execute `push` operation with a personal access token. + +## Preventing infinite loops + +The CI is configured to avoid infinite loops by only regenerating and pushing the `cargo vet` exemptions if the CI run happens with respect to a PR opened by dependabot and not for any other pushed or pull requests. In addition one of the following conditions has to be met: + +- The last commit was performed by dependabot +- The last commit message ends in `--regenerate-exemptions` + +Summarizing, the exemptions are only regenerated in the context of pull requests opened by dependabot and, the last commit was was performed by dependabot or the last commit message ends in `--regenerate-exemptions`. diff --git a/supply-chain/config.toml b/supply-chain/config.toml index c8673d10..a261f9a3 100644 --- a/supply-chain/config.toml +++ b/supply-chain/config.toml @@ -54,27 +54,27 @@ version = "0.2.15" criteria = "safe-to-run" [[exemptions.anstream]] -version = "0.6.15" +version = "0.6.18" criteria = "safe-to-deploy" [[exemptions.anstyle]] -version = "1.0.8" +version = "1.0.10" criteria = "safe-to-deploy" [[exemptions.anstyle-parse]] -version = "0.2.5" +version = "0.2.6" criteria = "safe-to-deploy" [[exemptions.anstyle-query]] -version = "1.1.1" +version = "1.1.2" criteria = "safe-to-deploy" [[exemptions.anstyle-wincon]] -version = "3.0.4" +version = "3.0.7" criteria = "safe-to-deploy" [[exemptions.anyhow]] -version = "1.0.95" +version = "1.0.96" criteria = "safe-to-deploy" [[exemptions.atomic-polyfill]] @@ -102,11 +102,11 @@ version = "0.1.4" criteria = "safe-to-deploy" [[exemptions.bytes]] -version = "1.7.2" +version = "1.10.0" criteria = "safe-to-deploy" [[exemptions.cc]] -version = "1.1.30" +version = "1.2.15" criteria = "safe-to-deploy" [[exemptions.chacha20]] @@ -117,36 +117,24 @@ criteria = "safe-to-deploy" version = "0.10.1" criteria = "safe-to-deploy" -[[exemptions.ciborium]] -version = "0.2.2" -criteria = "safe-to-run" - -[[exemptions.ciborium-io]] -version = "0.2.2" -criteria = "safe-to-run" - -[[exemptions.ciborium-ll]] -version = "0.2.2" -criteria = "safe-to-run" - [[exemptions.clang-sys]] version = "1.8.1" criteria = "safe-to-deploy" [[exemptions.clap]] -version = "4.5.23" +version = "4.5.30" criteria = "safe-to-deploy" [[exemptions.clap_builder]] -version = "4.5.23" +version = "4.5.30" criteria = "safe-to-deploy" [[exemptions.clap_complete]] -version = "4.5.40" +version = "4.5.45" criteria = "safe-to-deploy" [[exemptions.clap_derive]] -version = "4.5.18" +version = "4.5.28" criteria = "safe-to-deploy" [[exemptions.clap_lex]] @@ -154,15 +142,15 @@ version = "0.7.4" criteria = "safe-to-deploy" [[exemptions.clap_mangen]] -version = "0.2.24" +version = "0.2.29" criteria = "safe-to-deploy" [[exemptions.cmake]] -version = "0.1.51" +version = "0.1.54" criteria = "safe-to-deploy" [[exemptions.colorchoice]] -version = "1.0.2" +version = "1.0.3" criteria = "safe-to-deploy" [[exemptions.command-fds]] @@ -170,7 +158,7 @@ version = "0.2.3" criteria = "safe-to-deploy" [[exemptions.cpufeatures]] -version = "0.2.14" +version = "0.2.17" criteria = "safe-to-deploy" [[exemptions.criterion]] @@ -185,6 +173,10 @@ criteria = "safe-to-run" version = "1.2.0" criteria = "safe-to-deploy" +[[exemptions.crossbeam-deque]] +version = "0.8.6" +criteria = "safe-to-run" + [[exemptions.crossbeam-utils]] version = "0.8.20" criteria = "safe-to-run" @@ -289,14 +281,6 @@ criteria = "safe-to-deploy" version = "0.2.15" criteria = "safe-to-deploy" -[[exemptions.gimli]] -version = "0.31.1" -criteria = "safe-to-deploy" - -[[exemptions.half]] -version = "2.4.1" -criteria = "safe-to-run" - [[exemptions.hash32]] version = "0.2.1" criteria = "safe-to-deploy" @@ -305,6 +289,30 @@ criteria = "safe-to-deploy" version = "0.15.2" criteria = "safe-to-deploy" +[[exemptions.hax-lib]] +version = "0.1.0" +criteria = "safe-to-deploy" + +[[exemptions.hax-lib]] +version = "0.2.0" +criteria = "safe-to-deploy" + +[[exemptions.hax-lib-macros]] +version = "0.1.0" +criteria = "safe-to-deploy" + +[[exemptions.hax-lib-macros]] +version = "0.2.0" +criteria = "safe-to-deploy" + +[[exemptions.hax-lib-macros-types]] +version = "0.1.0" +criteria = "safe-to-deploy" + +[[exemptions.hax-lib-macros-types]] +version = "0.2.0" +criteria = "safe-to-deploy" + [[exemptions.heapless]] version = "0.7.17" criteria = "safe-to-deploy" @@ -325,8 +333,8 @@ criteria = "safe-to-deploy" version = "2.1.0" criteria = "safe-to-deploy" -[[exemptions.indexmap]] -version = "2.6.0" +[[exemptions.io-uring]] +version = "0.7.9" criteria = "safe-to-deploy" [[exemptions.ipc-channel]] @@ -334,7 +342,7 @@ version = "0.18.3" criteria = "safe-to-run" [[exemptions.is-terminal]] -version = "0.4.13" +version = "0.4.15" criteria = "safe-to-deploy" [[exemptions.is_terminal_polyfill]] @@ -346,7 +354,11 @@ version = "0.1.32" criteria = "safe-to-deploy" [[exemptions.js-sys]] -version = "0.3.72" +version = "0.3.77" +criteria = "safe-to-deploy" + +[[exemptions.keccak]] +version = "0.1.5" criteria = "safe-to-deploy" [[exemptions.lazycell]] @@ -354,23 +366,51 @@ version = "1.3.0" criteria = "safe-to-deploy" [[exemptions.libc]] -version = "0.2.168" +version = "0.2.174" criteria = "safe-to-deploy" [[exemptions.libcrux]] version = "0.0.2-pre.2" criteria = "safe-to-deploy" +[[exemptions.libcrux-chacha20poly1305]] +version = "0.0.2" +criteria = "safe-to-deploy" + [[exemptions.libcrux-hacl]] version = "0.0.2-pre.2" criteria = "safe-to-deploy" +[[exemptions.libcrux-hacl-rs]] +version = "0.0.2" +criteria = "safe-to-deploy" + +[[exemptions.libcrux-intrinsics]] +version = "0.0.2" +criteria = "safe-to-deploy" + +[[exemptions.libcrux-macros]] +version = "0.0.2" +criteria = "safe-to-deploy" + +[[exemptions.libcrux-ml-kem]] +version = "0.0.2-beta.3" +criteria = "safe-to-deploy" + [[exemptions.libcrux-platform]] version = "0.0.2-pre.2" criteria = "safe-to-deploy" +[[exemptions.libcrux-poly1305]] +version = "0.0.2" +criteria = "safe-to-deploy" + +[[exemptions.libcrux-sha3]] +version = "0.0.2-beta.3" +criteria = "safe-to-deploy" + [[exemptions.libfuzzer-sys]] -version = "0.4.8" +version = "0.4.9" criteria = "safe-to-deploy" [[exemptions.libjade-sys]] @@ -378,11 +418,11 @@ version = "0.0.2-pre.2" criteria = "safe-to-deploy" [[exemptions.libloading]] -version = "0.8.5" +version = "0.8.6" criteria = "safe-to-deploy" [[exemptions.linux-raw-sys]] -version = "0.4.14" +version = "0.4.15" criteria = "safe-to-deploy" [[exemptions.lock_api]] @@ -418,7 +458,7 @@ version = "0.6.3" criteria = "safe-to-deploy" [[exemptions.neli-proc-macros]] -version = "0.1.3" +version = "0.1.4" criteria = "safe-to-deploy" [[exemptions.netlink-packet-core]] @@ -442,11 +482,11 @@ version = "0.2.3" criteria = "safe-to-deploy" [[exemptions.netlink-proto]] -version = "0.11.3" +version = "0.11.5" criteria = "safe-to-deploy" [[exemptions.netlink-sys]] -version = "0.8.6" +version = "0.8.7" criteria = "safe-to-deploy" [[exemptions.nix]] @@ -457,8 +497,12 @@ criteria = "safe-to-deploy" version = "0.27.1" criteria = "safe-to-deploy" +[[exemptions.num-bigint]] +version = "0.4.6" +criteria = "safe-to-deploy" + [[exemptions.object]] -version = "0.36.5" +version = "0.36.7" criteria = "safe-to-deploy" [[exemptions.once_cell]] @@ -510,7 +554,11 @@ version = "0.2.20" criteria = "safe-to-deploy" [[exemptions.prettyplease]] -version = "0.2.22" +version = "0.2.29" +criteria = "safe-to-deploy" + +[[exemptions.proc-macro-error]] +version = "1.0.4" criteria = "safe-to-deploy" [[exemptions.procspawn]] @@ -518,23 +566,23 @@ version = "1.0.1" criteria = "safe-to-run" [[exemptions.psm]] -version = "0.1.23" +version = "0.1.25" criteria = "safe-to-deploy" [[exemptions.rand]] -version = "0.8.5" +version = "0.9.0" criteria = "safe-to-deploy" [[exemptions.redox_syscall]] -version = "0.5.7" +version = "0.5.9" criteria = "safe-to-deploy" [[exemptions.regex]] -version = "1.11.0" +version = "1.11.1" criteria = "safe-to-deploy" [[exemptions.regex-automata]] -version = "0.4.8" +version = "0.4.9" criteria = "safe-to-deploy" [[exemptions.roff]] @@ -546,15 +594,15 @@ version = "0.14.1" criteria = "safe-to-deploy" [[exemptions.rustix]] -version = "0.38.42" +version = "0.38.44" criteria = "safe-to-deploy" [[exemptions.ryu]] -version = "1.0.18" -criteria = "safe-to-run" +version = "1.0.19" +criteria = "safe-to-deploy" [[exemptions.scc]] -version = "2.2.1" +version = "2.3.3" criteria = "safe-to-run" [[exemptions.scopeguard]] @@ -562,9 +610,13 @@ version = "1.2.0" criteria = "safe-to-deploy" [[exemptions.sdd]] -version = "3.0.4" +version = "3.0.7" criteria = "safe-to-run" +[[exemptions.serde_json]] +version = "1.0.139" +criteria = "safe-to-deploy" + [[exemptions.serde_spanned]] version = "0.6.8" criteria = "safe-to-deploy" @@ -590,7 +642,7 @@ version = "0.4.9" criteria = "safe-to-deploy" [[exemptions.socket2]] -version = "0.5.7" +version = "0.6.0" criteria = "safe-to-deploy" [[exemptions.spin]] @@ -598,7 +650,7 @@ version = "0.9.8" criteria = "safe-to-deploy" [[exemptions.stacker]] -version = "0.1.17" +version = "0.1.19" criteria = "safe-to-deploy" [[exemptions.syn]] @@ -606,7 +658,7 @@ version = "1.0.109" criteria = "safe-to-deploy" [[exemptions.syn]] -version = "2.0.87" +version = "2.0.98" criteria = "safe-to-deploy" [[exemptions.take-until]] @@ -614,7 +666,7 @@ version = "0.1.0" criteria = "safe-to-deploy" [[exemptions.tempfile]] -version = "3.14.0" +version = "3.17.1" criteria = "safe-to-deploy" [[exemptions.termcolor]] @@ -626,19 +678,19 @@ version = "0.4.0" criteria = "safe-to-run" [[exemptions.thiserror]] -version = "1.0.69" +version = "2.0.11" criteria = "safe-to-deploy" [[exemptions.thiserror-impl]] -version = "1.0.69" +version = "2.0.11" criteria = "safe-to-deploy" [[exemptions.tokio]] -version = "1.42.0" +version = "1.47.0" criteria = "safe-to-deploy" [[exemptions.tokio-macros]] -version = "2.4.0" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.toml]] @@ -654,20 +706,20 @@ version = "0.19.15" criteria = "safe-to-deploy" [[exemptions.typenum]] -version = "1.17.0" +version = "1.18.0" criteria = "safe-to-deploy" [[exemptions.uds]] version = "0.4.2@git:b47934fe52422e559f7278938875f9105f91c5a2" criteria = "safe-to-deploy" -[[exemptions.utf8parse]] -version = "0.2.2" +[[exemptions.unicode-ident]] +version = "1.0.17" criteria = "safe-to-deploy" [[exemptions.uuid]] -version = "1.10.0" -criteria = "safe-to-run" +version = "1.14.0" +criteria = "safe-to-deploy" [[exemptions.version_check]] version = "0.9.5" @@ -681,28 +733,32 @@ criteria = "safe-to-run" version = "0.11.0+wasi-snapshot-preview1" criteria = "safe-to-deploy" +[[exemptions.wasi]] +version = "0.13.3+wasi-0.2.2" +criteria = "safe-to-deploy" + [[exemptions.wasm-bindgen]] -version = "0.2.95" +version = "0.2.100" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-backend]] -version = "0.2.95" +version = "0.2.100" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-macro]] -version = "0.2.95" +version = "0.2.100" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-macro-support]] -version = "0.2.95" +version = "0.2.100" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-shared]] -version = "0.2.95" +version = "0.2.100" criteria = "safe-to-deploy" [[exemptions.web-sys]] -version = "0.3.72" +version = "0.3.77" criteria = "safe-to-run" [[exemptions.which]] @@ -881,6 +937,14 @@ criteria = "safe-to-deploy" version = "0.7.35" criteria = "safe-to-deploy" +[[exemptions.zerocopy]] +version = "0.8.24" +criteria = "safe-to-deploy" + [[exemptions.zerocopy-derive]] version = "0.7.35" criteria = "safe-to-deploy" + +[[exemptions.zerocopy-derive]] +version = "0.8.24" +criteria = "safe-to-deploy" diff --git a/supply-chain/imports.lock b/supply-chain/imports.lock index 9f7c927a..2b5306ea 100644 --- a/supply-chain/imports.lock +++ b/supply-chain/imports.lock @@ -2,8 +2,8 @@ # cargo-vet imports lock [[publisher.bumpalo]] -version = "3.16.0" -when = "2024-04-08" +version = "3.17.0" +when = "2025-01-28" user-id = 696 user-login = "fitzgen" user-name = "Nick Fitzgerald" @@ -15,6 +15,12 @@ user-id = 3788 user-login = "emilio" user-name = "Emilio Cobos Álvarez" +[[publisher.wit-bindgen-rt]] +version = "0.33.0" +when = "2024-09-30" +user-id = 73222 +user-login = "wasmtime-publish" + [audits.actix.audits] [[audits.bytecode-alliance.wildcard-audits.bumpalo]] @@ -24,6 +30,18 @@ user-id = 696 # Nick Fitzgerald (fitzgen) start = "2019-03-16" end = "2025-07-30" +[[audits.bytecode-alliance.wildcard-audits.wit-bindgen-rt]] +who = "Alex Crichton " +criteria = "safe-to-deploy" +user-id = 73222 # wasmtime-publish +start = "2023-01-01" +end = "2026-06-03" +notes = """ +The Bytecode Alliance uses the `wasmtime-publish` crates.io account to automate +publication of this crate from CI. This repository requires all PRs are reviewed +by a Bytecode Alliance maintainer and it owned by the Bytecode Alliance itself. +""" + [[audits.bytecode-alliance.audits.adler2]] who = "Alex Crichton " criteria = "safe-to-deploy" @@ -103,12 +121,6 @@ who = "Benjamin Bouvier " criteria = "safe-to-deploy" version = "0.1.3" -[[audits.bytecode-alliance.audits.either]] -who = "Alex Crichton " -criteria = "safe-to-deploy" -delta = "1.8.1 -> 1.13.0" -notes = "More utilities and such for the `Either` type, no `unsafe` code." - [[audits.bytecode-alliance.audits.embedded-io]] who = "Alex Crichton " criteria = "safe-to-deploy" @@ -141,6 +153,12 @@ This update had a few doc updates but no otherwise-substantial source code updates. """ +[[audits.bytecode-alliance.audits.fastrand]] +who = "Alex Crichton " +criteria = "safe-to-deploy" +delta = "2.1.1 -> 2.3.0" +notes = "Minor refactoring, nothing new." + [[audits.bytecode-alliance.audits.futures]] who = "Joel Dice " criteria = "safe-to-deploy" @@ -187,6 +205,18 @@ who = "Pat Hickey " criteria = "safe-to-deploy" delta = "0.3.28 -> 0.3.31" +[[audits.bytecode-alliance.audits.gimli]] +who = "Alex Crichton " +criteria = "safe-to-deploy" +delta = "0.29.0 -> 0.31.0" +notes = "Various updates here and there, nothing too major, what you'd expect from a DWARF parsing crate." + +[[audits.bytecode-alliance.audits.gimli]] +who = "Alex Crichton " +criteria = "safe-to-deploy" +delta = "0.31.0 -> 0.31.1" +notes = "No fundmanetally new `unsafe` code, some small refactoring of existing code. Lots of changes in tests, not as many changes in the rest of the crate. More dwarf!" + [[audits.bytecode-alliance.audits.heck]] who = "Alex Crichton " criteria = "safe-to-deploy" @@ -199,6 +229,11 @@ criteria = "safe-to-deploy" version = "0.1.3" notes = "A part of RustCrypto/utils, this crate is designed to handle unsafe buffers and carefully documents the safety concerns throughout. Older versions of this tally up to ~130k daily downloads." +[[audits.bytecode-alliance.audits.itoa]] +who = "Dan Gohman " +criteria = "safe-to-deploy" +delta = "1.0.11 -> 1.0.14" + [[audits.bytecode-alliance.audits.miniz_oxide]] who = "Alex Crichton " criteria = "safe-to-deploy" @@ -219,6 +254,16 @@ criteria = "safe-to-deploy" delta = "0.7.1 -> 0.8.0" notes = "Minor updates, using new Rust features like `const`, no major changes." +[[audits.bytecode-alliance.audits.miniz_oxide]] +who = "Alex Crichton " +criteria = "safe-to-deploy" +delta = "0.8.0 -> 0.8.5" +notes = """ +Lots of small updates here and there, for example around modernizing Rust +idioms. No new `unsafe` code and everything looks like what you'd expect a +compression library to be doing. +""" + [[audits.bytecode-alliance.audits.num-traits]] who = "Andrew Brown " criteria = "safe-to-deploy" @@ -277,6 +322,24 @@ criteria = "safe-to-deploy" version = "1.0.1" notes = "No unsafe usage or ambient capabilities" +[[audits.embark-studios.audits.thiserror]] +who = "Johan Andersson " +criteria = "safe-to-deploy" +version = "1.0.40" +notes = "Wrapper over implementation crate, found no unsafe or ambient capabilities used" + +[[audits.embark-studios.audits.thiserror-impl]] +who = "Johan Andersson " +criteria = "safe-to-deploy" +version = "1.0.40" +notes = "Found no unsafe or ambient capabilities used" + +[[audits.embark-studios.audits.utf8parse]] +who = "Johan Andersson " +criteria = "safe-to-deploy" +version = "0.2.1" +notes = "Single unsafe usage that looks sound, no ambient capabilities" + [[audits.fermyon.audits.oorandom]] who = "Radu Matei " criteria = "safe-to-run" @@ -305,6 +368,13 @@ Additional review comments can be found at https://crrev.com/c/4723145/31 """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.bitflags]] +who = "Lukasz Anforowicz " +criteria = "safe-to-deploy" +delta = "2.6.0 -> 2.8.0" +notes = "No changes related to `unsafe impl ... bytemuck` pieces from `src/external.rs`." +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.byteorder]] who = "danakj " criteria = "safe-to-deploy" @@ -318,6 +388,24 @@ criteria = "safe-to-run" version = "0.3.0" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" +[[audits.google.audits.ciborium]] +who = "Daniel Verkamp " +criteria = "safe-to-run" +version = "0.2.2" +aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" + +[[audits.google.audits.ciborium-io]] +who = "Daniel Verkamp " +criteria = "safe-to-run" +version = "0.2.2" +aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" + +[[audits.google.audits.ciborium-ll]] +who = "Daniel Verkamp " +criteria = "safe-to-run" +version = "0.2.2" +aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" + [[audits.google.audits.crossbeam-channel]] who = "George Burgess IV " criteria = "safe-to-run" @@ -330,12 +418,6 @@ criteria = "safe-to-run" delta = "0.5.7 -> 0.5.8" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" -[[audits.google.audits.crossbeam-deque]] -who = "George Burgess IV " -criteria = "safe-to-run" -version = "0.8.3" -aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" - [[audits.google.audits.crossbeam-epoch]] who = "George Burgess IV " criteria = "safe-to-run" @@ -348,12 +430,26 @@ criteria = "safe-to-run" delta = "0.9.14 -> 0.9.15" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" +[[audits.google.audits.either]] +who = "Manish Goregaokar " +criteria = "safe-to-deploy" +version = "1.13.0" +notes = "Unsafe code pertaining to wrapping Pin APIs. Mostly passes invariants down." +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.equivalent]] who = "George Burgess IV " criteria = "safe-to-deploy" version = "1.0.1" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" +[[audits.google.audits.equivalent]] +who = "Jonathan Hao " +criteria = "safe-to-deploy" +delta = "1.0.1 -> 1.0.2" +notes = "No changes to any .rs files or Rust code." +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.fastrand]] who = "George Burgess IV " criteria = "safe-to-deploy" @@ -370,6 +466,19 @@ criteria = "safe-to-deploy" version = "0.3.1" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" +[[audits.google.audits.glob]] +who = "Dustin J. Mitchell " +criteria = "safe-to-deploy" +delta = "0.3.1 -> 0.3.2" +notes = "Still no unsafe" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.half]] +who = "Daniel Verkamp " +criteria = "safe-to-run" +version = "2.4.1" +aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" + [[audits.google.audits.heck]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" @@ -383,6 +492,19 @@ https://source.chromium.org/chromium/chromium/src/+/28841c33c77833cc30b286f9ae24 """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.indexmap]] +who = "Lukasz Anforowicz " +criteria = "safe-to-deploy" +version = "2.7.1" +notes = ''' +Grepped for `-i cipher`, `-i crypto`, `'\bfs\b'`, `'\bnet\b'` +and there were no hits. + +There is a little bit of `unsafe` Rust code - the audit can be found at +https://chromium-review.googlesource.com/c/chromium/src/+/6187726/2 +''' +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.itertools]] who = "ChromeOS" criteria = "safe-to-run" @@ -451,6 +573,20 @@ describe in the review doc. """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.log]] +who = "Lukasz Anforowicz " +criteria = "safe-to-deploy" +delta = "0.4.22 -> 0.4.25" +notes = "No impact on `unsafe` usage in `lib.rs`." +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.log]] +who = "Daniel Cheng " +criteria = "safe-to-deploy" +delta = "0.4.25 -> 0.4.26" +notes = "Only trivial code and documentation changes." +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.nom]] who = "danakj@chromium.org" criteria = "safe-to-deploy" @@ -460,6 +596,13 @@ Reviewed in https://chromium-review.googlesource.com/c/chromium/src/+/5046153 """ aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.num-integer]] +who = "Manish Goregaokar " +criteria = "safe-to-deploy" +version = "0.1.46" +notes = "Contains no unsafe" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.pin-project-lite]] who = "David Koloski " criteria = "safe-to-deploy" @@ -474,6 +617,12 @@ delta = "0.2.9 -> 0.2.13" notes = "Audited at https://fxrev.dev/946396" aggregated-from = "https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/third_party/rust_crates/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.proc-macro-error-attr]] +who = "George Burgess IV " +criteria = "safe-to-deploy" +version = "1.0.4" +aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" + [[audits.google.audits.proc-macro2]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" @@ -551,6 +700,35 @@ delta = "1.0.86 -> 1.0.87" notes = "No new unsafe interactions." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.proc-macro2]] +who = "Liza Burakova Qualifiers::Unsafe, + ``` + +* Using `std::fs` in `build/build.rs` to write `${OUT_DIR}/version.expr` + which is later read back via `include!` used in `src/lib.rs`. + +Version `1.0.6` of this crate has been added to Chromium in +https://source.chromium.org/chromium/chromium/src/+/28841c33c77833cc30b286f9ae24c97e7a8f4057 +""" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.rustversion]] +who = "Adrian Taylor " +criteria = "safe-to-deploy" +delta = "1.0.14 -> 1.0.15" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.rustversion]] +who = "danakj " +criteria = "safe-to-deploy" +delta = "1.0.15 -> 1.0.16" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.rustversion]] +who = "Dustin J. Mitchell " +criteria = "safe-to-deploy" +delta = "1.0.16 -> 1.0.17" +notes = "Just updates windows compat" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.rustversion]] +who = "Liza Burakova " +criteria = "safe-to-deploy" +delta = "1.0.17 -> 1.0.18" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + +[[audits.google.audits.rustversion]] +who = "Dustin J. Mitchell " +criteria = "safe-to-deploy" +delta = "1.0.18 -> 1.0.19" +notes = "No unsafe, just doc changes" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.same-file]] who = "Android Legacy" criteria = "safe-to-run" @@ -704,6 +977,13 @@ delta = "1.0.216 -> 1.0.217" notes = "Minimal changes, nothing unsafe" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.serde]] +who = "Daniel Cheng " +criteria = "safe-to-deploy" +delta = "1.0.217 -> 1.0.218" +notes = "No changes outside comments and documentation." +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.serde_derive]] who = "Lukasz Anforowicz " criteria = "safe-to-deploy" @@ -797,51 +1077,11 @@ delta = "1.0.216 -> 1.0.217" notes = "No changes" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" -[[audits.google.audits.serde_json]] -who = "danakj@chromium.org" -criteria = "safe-to-run" -version = "1.0.108" -notes = """ -Reviewed in https://crrev.com/c/5171063 - -Previously reviewed during security review and the audit is grandparented in. -""" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.serde_json]] -who = "danakj " -criteria = "safe-to-run" -delta = "1.0.116 -> 1.0.117" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.serde_json]] -who = "Adrian Taylor " -criteria = "safe-to-run" -delta = "1.0.117 -> 1.0.120" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.serde_json]] -who = "Lukasz Anforowicz " -criteria = "safe-to-run" -delta = "1.0.120 -> 1.0.122" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.serde_json]] -who = "Lukasz Anforowicz " -criteria = "safe-to-run" -delta = "1.0.122 -> 1.0.124" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.serde_json]] -who = "Lukasz Anforowicz " -criteria = "safe-to-run" -delta = "1.0.124 -> 1.0.127" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.serde_json]] -who = "danakj " -criteria = "safe-to-run" -delta = "1.0.127 -> 1.0.128" +[[audits.google.audits.serde_derive]] +who = "Daniel Cheng " +criteria = "safe-to-deploy" +delta = "1.0.217 -> 1.0.218" +notes = "No changes outside comments and documentation." aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" [[audits.google.audits.small_ctor]] @@ -868,6 +1108,20 @@ criteria = "safe-to-deploy" version = "1.13.2" aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" +[[audits.google.audits.smallvec]] +who = "Jonathan Hao " +criteria = "safe-to-deploy" +delta = "1.13.2 -> 1.14.0" +notes = """ +WARNING: This certification is a result of a **partial** audit. The +`malloc_size_of` feature has **not** been audited. This feature does +not explicitly document its safety requirements. +See also https://chromium-review.googlesource.com/c/chromium/src/+/6275133/comment/ea0d7a93_98051a2e/ +and https://github.com/servo/malloc_size_of/issues/8. +This feature is banned in gnrt_config.toml. +""" +aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" + [[audits.google.audits.stable_deref_trait]] who = "Manish Goregaokar " criteria = "safe-to-deploy" @@ -892,44 +1146,11 @@ criteria = "safe-to-run" version = "1.2.1" aggregated-from = "https://chromium.googlesource.com/chromiumos/third_party/rust_crates/+/refs/heads/main/cargo-vet/audits.toml?format=TEXT" -[[audits.google.audits.unicode-ident]] -who = "Lukasz Anforowicz " -criteria = "safe-to-deploy" -version = "1.0.12" -notes = ''' -I grepped for \"crypt\", \"cipher\", \"fs\", \"net\" - there were no hits. - -All two functions from the public API of this crate use `unsafe` to avoid bound -checks for an array access. Cross-module analysis shows that the offsets can -be statically proven to be within array bounds. More details can be found in -the unsafe review CL at https://crrev.com/c/5350386. - -This crate has been added to Chromium in https://crrev.com/c/3891618. -''' -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - -[[audits.google.audits.unicode-ident]] -who = "Dustin J. Mitchell " -criteria = "safe-to-deploy" -delta = "1.0.12 -> 1.0.13" -notes = "Lots of table updates, and tables are assumed correct with unsafe `.get_unchecked()`, so ub-risk-2 is appropriate" -aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT" - [[audits.isrg.audits.block-buffer]] who = "David Cook " criteria = "safe-to-deploy" version = "0.9.0" -[[audits.isrg.audits.crunchy]] -who = "David Cook " -criteria = "safe-to-deploy" -version = "0.2.2" - -[[audits.isrg.audits.either]] -who = "David Cook " -criteria = "safe-to-deploy" -version = "1.6.1" - [[audits.isrg.audits.fiat-crypto]] who = "David Cook " criteria = "safe-to-deploy" @@ -1018,12 +1239,12 @@ version = "0.3.0" [[audits.isrg.audits.rand_chacha]] who = "David Cook " criteria = "safe-to-deploy" -version = "0.3.1" +delta = "0.3.1 -> 0.9.0" [[audits.isrg.audits.rand_core]] who = "David Cook " criteria = "safe-to-deploy" -version = "0.6.3" +delta = "0.6.4 -> 0.9.3" [[audits.isrg.audits.rayon]] who = "Brandon Pitman " @@ -1055,11 +1276,36 @@ who = "Ameer Ghani " criteria = "safe-to-deploy" version = "1.12.1" +[[audits.isrg.audits.sha3]] +who = "David Cook " +criteria = "safe-to-deploy" +version = "0.10.6" + +[[audits.isrg.audits.sha3]] +who = "Brandon Pitman " +criteria = "safe-to-deploy" +delta = "0.10.6 -> 0.10.7" + +[[audits.isrg.audits.sha3]] +who = "Brandon Pitman " +criteria = "safe-to-deploy" +delta = "0.10.7 -> 0.10.8" + [[audits.isrg.audits.subtle]] who = "David Cook " criteria = "safe-to-deploy" delta = "2.5.0 -> 2.6.1" +[[audits.isrg.audits.thiserror]] +who = "Brandon Pitman " +criteria = "safe-to-deploy" +delta = "1.0.40 -> 1.0.43" + +[[audits.isrg.audits.thiserror-impl]] +who = "Brandon Pitman " +criteria = "safe-to-deploy" +delta = "1.0.40 -> 1.0.43" + [[audits.isrg.audits.universal-hash]] who = "David Cook " criteria = "safe-to-deploy" @@ -1173,6 +1419,25 @@ criteria = "safe-to-deploy" delta = "0.5.12 -> 0.5.13" aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +[[audits.mozilla.audits.crossbeam-channel]] +who = "Jan-Erik Rediger " +criteria = "safe-to-deploy" +delta = "0.5.13 -> 0.5.14" +aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml" + +[[audits.mozilla.audits.crossbeam-channel]] +who = "Jan-Erik Rediger " +criteria = "safe-to-deploy" +delta = "0.5.14 -> 0.5.15" +notes = "Fixes a regression from an earlier version which could lead to a double free" +aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml" + +[[audits.mozilla.audits.crunchy]] +who = "Erich Gubler " +criteria = "safe-to-deploy" +version = "0.2.3" +aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" + [[audits.mozilla.audits.crypto-common]] who = "Mike Hommey " criteria = "safe-to-deploy" @@ -1189,24 +1454,6 @@ comments on older versions of rustc. """ aggregated-from = "https://raw.githubusercontent.com/mozilla/cargo-vet/main/supply-chain/audits.toml" -[[audits.mozilla.audits.either]] -who = "Mike Hommey " -criteria = "safe-to-deploy" -delta = "1.6.1 -> 1.7.0" -aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" - -[[audits.mozilla.audits.either]] -who = "Mike Hommey " -criteria = "safe-to-deploy" -delta = "1.7.0 -> 1.8.0" -aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" - -[[audits.mozilla.audits.either]] -who = "Mike Hommey " -criteria = "safe-to-deploy" -delta = "1.8.0 -> 1.8.1" -aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" - [[audits.mozilla.audits.errno]] who = "Mike Hommey " criteria = "safe-to-deploy" @@ -1225,6 +1472,13 @@ criteria = "safe-to-deploy" delta = "2.0.1 -> 2.1.0" aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +[[audits.mozilla.audits.fastrand]] +who = "Chris Martin " +criteria = "safe-to-deploy" +delta = "2.1.0 -> 2.1.1" +notes = "Fairly trivial changes, no chance of security regression." +aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" + [[audits.mozilla.audits.fnv]] who = "Bobby Holley " criteria = "safe-to-deploy" @@ -1244,12 +1498,46 @@ criteria = "safe-to-deploy" delta = "0.3.27 -> 0.3.28" aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +[[audits.mozilla.audits.getrandom]] +who = "Chris Martin " +criteria = "safe-to-deploy" +delta = "0.2.15 -> 0.3.1" +notes = """ +I've looked over all unsafe code, and it appears to be safe, fully initializing the rng buffers. +In addition, I've checked Linux, Windows, Mac, and Android more thoroughly against API +documentation. +""" +aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" + +[[audits.mozilla.audits.gimli]] +who = "Alex Franchuk " +criteria = "safe-to-deploy" +version = "0.30.0" +notes = """ +Unsafe code blocks are sound. Minimal dependencies used. No use of +side-effectful std functions. +""" +aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" + +[[audits.mozilla.audits.gimli]] +who = "Chris Martin " +criteria = "safe-to-deploy" +delta = "0.30.0 -> 0.29.0" +notes = "No unsafe code, mostly algorithms and parsing. Very unlikely to cause security issues." +aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" + [[audits.mozilla.audits.hex]] who = "Simon Friedberger " criteria = "safe-to-deploy" version = "0.4.3" aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +[[audits.mozilla.audits.once_cell]] +who = "Erich Gubler " +criteria = "safe-to-deploy" +delta = "1.20.2 -> 1.20.3" +aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" + [[audits.mozilla.audits.peeking_take_while]] who = "Bobby Holley " criteria = "safe-to-deploy" @@ -1257,11 +1545,15 @@ delta = "1.0.0 -> 0.1.2" notes = "Small refactor of some simple iterator logic, no unsafe code or capabilities." aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" -[[audits.mozilla.audits.rand_core]] -who = "Mike Hommey " +[[audits.mozilla.audits.pin-project-lite]] +who = "Nika Layzell " criteria = "safe-to-deploy" -delta = "0.6.3 -> 0.6.4" -aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +delta = "0.2.14 -> 0.2.16" +notes = """ +Only functional change is to work around a bug in the negative_impls feature +(https://github.com/taiki-e/pin-project/issues/340#issuecomment-2432146009) +""" +aggregated-from = "https://raw.githubusercontent.com/mozilla/cargo-vet/main/supply-chain/audits.toml" [[audits.mozilla.audits.rayon]] who = "Josh Stone " @@ -1283,6 +1575,12 @@ version = "1.1.0" notes = "Straightforward crate with no unsafe code, does what it says on the tin." aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +[[audits.mozilla.audits.semver]] +who = "Jan-Erik Rediger " +criteria = "safe-to-deploy" +delta = "1.0.17 -> 1.0.25" +aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml" + [[audits.mozilla.audits.shlex]] who = "Max Inden " criteria = "safe-to-deploy" @@ -1302,6 +1600,24 @@ version = "2.5.0" notes = "The goal is to provide some constant-time correctness for cryptographic implementations. The approach is reasonable, it is known to be insufficient but this is pointed out in the documentation." aggregated-from = "https://hg.mozilla.org/mozilla-central/raw-file/tip/supply-chain/audits.toml" +[[audits.mozilla.audits.thiserror]] +who = "Jan-Erik Rediger " +criteria = "safe-to-deploy" +delta = "1.0.43 -> 1.0.69" +aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml" + +[[audits.mozilla.audits.thiserror-impl]] +who = "Jan-Erik Rediger " +criteria = "safe-to-deploy" +delta = "1.0.43 -> 1.0.69" +aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml" + +[[audits.mozilla.audits.utf8parse]] +who = "Nika Layzell " +criteria = "safe-to-deploy" +delta = "0.2.1 -> 0.2.2" +aggregated-from = "https://raw.githubusercontent.com/mozilla/cargo-vet/main/supply-chain/audits.toml" + [[audits.mozilla.audits.zeroize]] who = "Benjamin Beurdouche " criteria = "safe-to-deploy" @@ -1325,17 +1641,10 @@ delta = "0.10.3 -> 0.10.4" notes = "Adds panics to prevent a block size of zero from causing unsoundness." aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" -[[audits.zcash.audits.crossbeam-deque]] +[[audits.zcash.audits.crossbeam-utils]] who = "Jack Grigg " criteria = "safe-to-deploy" -delta = "0.8.3 -> 0.8.4" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - -[[audits.zcash.audits.crossbeam-deque]] -who = "Daira-Emma Hopwood " -criteria = "safe-to-deploy" -delta = "0.8.4 -> 0.8.5" -notes = "Changes to `unsafe` code look okay." +delta = "0.8.20 -> 0.8.21" aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" [[audits.zcash.audits.errno]] @@ -1350,11 +1659,11 @@ criteria = "safe-to-deploy" delta = "0.3.8 -> 0.3.9" aggregated-from = "https://raw.githubusercontent.com/zcash/librustzcash/main/supply-chain/audits.toml" -[[audits.zcash.audits.fastrand]] +[[audits.zcash.audits.inout]] who = "Jack Grigg " criteria = "safe-to-deploy" -delta = "2.1.0 -> 2.1.1" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" +delta = "0.1.3 -> 0.1.4" +aggregated-from = "https://raw.githubusercontent.com/zcash/wallet/main/supply-chain/audits.toml" [[audits.zcash.audits.oorandom]] who = "Jack Grigg " @@ -1390,52 +1699,6 @@ delta = "0.4.0 -> 0.4.1" notes = "Changes to `Command` usage are to add support for `RUSTC_WRAPPER`." aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" -[[audits.zcash.audits.semver]] -who = "Jack Grigg " -criteria = "safe-to-deploy" -delta = "1.0.17 -> 1.0.18" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - -[[audits.zcash.audits.semver]] -who = "Jack Grigg " -criteria = "safe-to-deploy" -delta = "1.0.18 -> 1.0.19" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - -[[audits.zcash.audits.semver]] -who = "Jack Grigg " -criteria = "safe-to-deploy" -delta = "1.0.19 -> 1.0.20" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - -[[audits.zcash.audits.semver]] -who = "Daira-Emma Hopwood " -criteria = "safe-to-deploy" -delta = "1.0.20 -> 1.0.22" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - -[[audits.zcash.audits.semver]] -who = "Jack Grigg " -criteria = "safe-to-deploy" -delta = "1.0.22 -> 1.0.23" -notes = """ -`build.rs` change is to enable checking for expected `#[cfg]` names if compiling -with Rust 1.80 or later. -""" -aggregated-from = "https://raw.githubusercontent.com/zcash/librustzcash/main/supply-chain/audits.toml" - -[[audits.zcash.audits.serde_json]] -who = "Jack Grigg " -criteria = "safe-to-deploy" -delta = "1.0.108 -> 1.0.110" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - -[[audits.zcash.audits.serde_json]] -who = "Daira-Emma Hopwood " -criteria = "safe-to-deploy" -delta = "1.0.110 -> 1.0.116" -aggregated-from = "https://raw.githubusercontent.com/zcash/zcash/master/qa/supply-chain/audits.toml" - [[audits.zcash.audits.universal-hash]] who = "Daira Hopwood " criteria = "safe-to-deploy" diff --git a/tests/legacy-distro-packaging.nix b/tests/legacy-distro-packaging.nix new file mode 100644 index 00000000..619dbfa2 --- /dev/null +++ b/tests/legacy-distro-packaging.nix @@ -0,0 +1,82 @@ +{ + pkgs, + rosenpass-deb, + rosenpass-rpm, +}: + +let + wg-deb = pkgs.fetchurl { + url = "https://ftp.de.debian.org/debian/pool/main/w/wireguard/wireguard-tools_1.0.20210914-1.1_amd64.deb"; + hash = "sha256-s/hCUisQLR19kEbV6d8JXzzTAWUPM+NV0APgHizRGA4="; + }; + wg-rpm = pkgs.fetchurl { + url = "https://mirrors.n-ix.net/fedora/linux/releases/40/Everything/x86_64/os/Packages/w/wireguard-tools-1.0.20210914-6.fc40.x86_64.rpm"; + hash = "sha256-lh6kCW5gh9bfuOwzjPv96ol1d6u1JTIr/oKH5QbAlK0="; + }; + + pkgsDirDeb = pkgs.runCommand "packages" { } '' + mkdir $out + cp ${rosenpass-deb} $out/rosenpass.deb + cp ${wg-deb} $out/wireguard.deb + cp ${./prepare-test.sh} $out/prepare-test.sh + ''; + pkgsDirRpm = pkgs.runCommand "packages" { } '' + mkdir $out + cp ${rosenpass-rpm} $out/rosenpass.rpm + cp ${wg-rpm} $out/wireguard.rpm + cp ${./prepare-test.sh} $out/prepare-test.sh + ''; + + test = + { + tester, + installPrefix, + suffix, + source, + }: + (tester { + sharedDirs.share = { + inherit source; + target = "/mnt/share"; + }; + testScript = '' + vm.wait_for_unit("multi-user.target") + vm.succeed("${installPrefix} /mnt/share/wireguard.${suffix}") + vm.succeed("${installPrefix} /mnt/share/rosenpass.${suffix}") + vm.succeed("bash /mnt/share/prepare-test.sh") + + vm.succeed(f"systemctl start rp@server") + vm.succeed(f"systemctl start rp@client") + + vm.wait_for_unit("rp@server.service") + vm.wait_for_unit("rp@client.service") + + vm.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); + + psk_server = vm.succeed("wg show rp-server preshared-keys").strip().split()[-1] + psk_client = vm.succeed("wg show rp-client preshared-keys").strip().split()[-1] + + assert psk_server == psk_client, "preshared-key exchange must be successful" + ''; + }).sandboxed; +in +{ + package-deb-debian-13 = test { + tester = pkgs.testers.nonNixOSDistros.debian."13"; + installPrefix = "dpkg --install"; + suffix = "deb"; + source = pkgsDirDeb; + }; + package-deb-ubuntu-23_10 = test { + tester = pkgs.testers.nonNixOSDistros.ubuntu."23_10"; + installPrefix = "dpkg --install"; + suffix = "deb"; + source = pkgsDirDeb; + }; + package-rpm-fedora_40 = test { + tester = pkgs.testers.nonNixOSDistros.fedora."40"; + installPrefix = "rpm -i"; + suffix = "rpm"; + source = pkgsDirRpm; + }; +} diff --git a/tests/prepare-test.sh b/tests/prepare-test.sh new file mode 100644 index 00000000..a10c97f9 --- /dev/null +++ b/tests/prepare-test.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash + +set -euxo pipefail + +< /etc/rosenpass/example.toml \ + sed 's@example@server@' > /etc/rosenpass/server.toml + +< /etc/rosenpass/example.toml \ + sed 's@listen.*@@' | + sed 's@client@server@' | + sed 's@example@client@' | + sed 's@fc00::2@fc00::1@' | + sed 's@fc00::1/64@fc00::2/64@' > /etc/rosenpass/client.toml + +echo 'endpoint = "[::1]:51821"' >> /etc/rosenpass/client.toml + +rp genkey server-sk +rp pubkey server-sk server-pk + +rp genkey client-sk +rp pubkey client-sk client-pk + +mkdir -p /etc/rosenpass/server/peers/client +mkdir -p /etc/rosenpass/client/peers/server + +cp server-sk/{pqpk,pqsk,wgsk} /etc/rosenpass/server/ +cp client-sk/{pqpk,pqsk,wgsk} /etc/rosenpass/client/ + +cp client-pk/{pqpk,wgpk} /etc/rosenpass/server/peers/client +cp server-pk/{pqpk,wgpk} /etc/rosenpass/client/peers/server diff --git a/tests/systemd/rosenpass.nix b/tests/systemd/rosenpass.nix index 18ca5d10..d1eddf82 100644 --- a/tests/systemd/rosenpass.nix +++ b/tests/systemd/rosenpass.nix @@ -32,29 +32,33 @@ let public_key = "/etc/rosenpass/rp0/pqpk"; secret_key = "/run/credentials/rosenpass@rp0.service/pqsk"; verbosity = "Verbose"; - peers = [{ - device = "rp0"; - peer = client.wg.public; - public_key = "/etc/rosenpass/rp0/peers/client/pqpk"; - }]; + peers = [ + { + device = "rp0"; + peer = client.wg.public; + public_key = "/etc/rosenpass/rp0/peers/client/pqpk"; + } + ]; }; client_config = { listen = [ ]; public_key = "/etc/rosenpass/rp0/pqpk"; secret_key = "/run/credentials/rosenpass@rp0.service/pqsk"; verbosity = "Verbose"; - peers = [{ - device = "rp0"; - peer = server.wg.public; - public_key = "/etc/rosenpass/rp0/peers/server/pqpk"; - endpoint = "${server.ip4}:9999"; - }]; + peers = [ + { + device = "rp0"; + peer = server.wg.public; + public_key = "/etc/rosenpass/rp0/peers/server/pqpk"; + endpoint = "${server.ip4}:9999"; + } + ]; }; config = pkgs.runCommand "config" { } '' mkdir -pv $out - cp -v ${(pkgs.formats.toml {}).generate "rp0.toml" server_config} $out/server - cp -v ${(pkgs.formats.toml {}).generate "rp0.toml" client_config} $out/client + cp -v ${(pkgs.formats.toml { }).generate "rp0.toml" server_config} $out/server + cp -v ${(pkgs.formats.toml { }).generate "rp0.toml" client_config} $out/client ''; in { @@ -62,50 +66,71 @@ in nodes = let - shared = peer: { config, modulesPath, pkgs, ... }: { - # Need to work around a problem in recent systemd changes. - # It won't be necessary in other distros (for which the systemd file was designed), this is NixOS specific - # https://github.com/NixOS/nixpkgs/issues/258371#issuecomment-1925672767 - # This can potentially be removed in future nixpkgs updates - systemd.packages = [ - (pkgs.runCommand "rosenpass" { } '' - mkdir -p $out/lib/systemd/system - < ${pkgs.rosenpass}/lib/systemd/system/rosenpass.target > $out/lib/systemd/system/rosenpass.target - < ${pkgs.rosenpass}/lib/systemd/system/rosenpass@.service \ - sed 's@^\(\[Service]\)$@\1\nEnvironment=PATH=${pkgs.wireguard-tools}/bin@' | - sed 's@^ExecStartPre=envsubst @ExecStartPre='"${pkgs.envsubst}"'/bin/envsubst @' | - sed 's@^ExecStart=rosenpass @ExecStart='"${pkgs.rosenpass}"'/bin/rosenpass @' > $out/lib/systemd/system/rosenpass@.service - '') - ]; - networking.wireguard = { - enable = true; - interfaces.rp0 = { - ips = [ "${peer.wg.ip4}/32" "${peer.wg.ip6}/128" ]; - privateKeyFile = "/etc/wireguard/wgsk"; + shared = + peer: + { + config, + modulesPath, + pkgs, + ... + }: + { + # Need to work around a problem in recent systemd changes. + # It won't be necessary in other distros (for which the systemd file was designed), this is NixOS specific + # https://github.com/NixOS/nixpkgs/issues/258371#issuecomment-1925672767 + # This can potentially be removed in future nixpkgs updates + systemd.packages = [ + (pkgs.runCommand "rosenpass" { } '' + mkdir -p $out/lib/systemd/system + < ${pkgs.rosenpass}/lib/systemd/system/rosenpass.target > $out/lib/systemd/system/rosenpass.target + < ${pkgs.rosenpass}/lib/systemd/system/rosenpass@.service \ + sed 's@^\(\[Service]\)$@\1\nEnvironment=PATH=${pkgs.wireguard-tools}/bin@' | + sed 's@^ExecStartPre=envsubst @ExecStartPre='"${pkgs.envsubst}"'/bin/envsubst @' | + sed 's@^ExecStart=rosenpass @ExecStart='"${pkgs.rosenpass}"'/bin/rosenpass @' > $out/lib/systemd/system/rosenpass@.service + '') + ]; + networking.wireguard = { + enable = true; + interfaces.rp0 = { + ips = [ + "${peer.wg.ip4}/32" + "${peer.wg.ip6}/128" + ]; + privateKeyFile = "/etc/wireguard/wgsk"; + }; + }; + environment.etc."wireguard/wgsk".text = peer.wg.secret; + networking.interfaces.eth1 = { + ipv4.addresses = [ + { + address = peer.ip4; + prefixLength = 24; + } + ]; + ipv6.addresses = [ + { + address = peer.ip6; + prefixLength = 64; + } + ]; }; }; - environment.etc."wireguard/wgsk".text = peer.wg.secret; - networking.interfaces.eth1 = { - ipv4.addresses = [{ - address = peer.ip4; - prefixLength = 24; - }]; - ipv6.addresses = [{ - address = peer.ip6; - prefixLength = 64; - }]; - }; - }; in { server = { imports = [ (shared server) ]; - networking.firewall.allowedUDPPorts = [ 9999 server.wg.listen ]; + networking.firewall.allowedUDPPorts = [ + 9999 + server.wg.listen + ]; networking.wireguard.interfaces.rp0 = { listenPort = server.wg.listen; peers = [ { - allowedIPs = [ client.wg.ip4 client.wg.ip6 ]; + allowedIPs = [ + client.wg.ip4 + client.wg.ip6 + ]; publicKey = client.wg.public; } ]; @@ -116,7 +141,10 @@ in networking.wireguard.interfaces.rp0 = { peers = [ { - allowedIPs = [ "10.23.42.0/24" "fc00::/64" ]; + allowedIPs = [ + "10.23.42.0/24" + "fc00::/64" + ]; publicKey = server.wg.public; endpoint = "${server.ip4}:${toString server.wg.listen}"; } @@ -124,60 +152,62 @@ in }; }; }; - testScript = { ... }: '' - from os import system - rosenpass = "${pkgs.rosenpass}/bin/rosenpass" + testScript = + { ... }: + '' + from os import system + rosenpass = "${pkgs.rosenpass}/bin/rosenpass" - start_all() - - for machine in [server, client]: - machine.wait_for_unit("multi-user.target") - machine.wait_for_unit("network-online.target") - - with subtest("Key, Config, and Service Setup"): - for name, machine, remote in [("server", server, client), ("client", client, server)]: - # generate all the keys - system(f"{rosenpass} gen-keys --public-key {name}-pqpk --secret-key {name}-pqsk") - - # copy private keys to our side - machine.copy_from_host(f"{name}-pqsk", "/etc/rosenpass/rp0/pqsk") - machine.copy_from_host(f"{name}-pqpk", "/etc/rosenpass/rp0/pqpk") - - # copy public keys to other side - remote.copy_from_host(f"{name}-pqpk", f"/etc/rosenpass/rp0/peers/{name}/pqpk") - - machine.copy_from_host(f"${config}/{name}", "/etc/rosenpass/rp0.toml") + start_all() for machine in [server, client]: - machine.wait_for_unit("wireguard-rp0.service") + machine.wait_for_unit("multi-user.target") + machine.wait_for_unit("network-online.target") - with subtest("wg network test"): - client.succeed("wg show all preshared-keys | grep none", timeout=5); - client.succeed("ping -c5 ${server.wg.ip4}") - server.succeed("ping -c5 ${client.wg.ip6}") + with subtest("Key, Config, and Service Setup"): + for name, machine, remote in [("server", server, client), ("client", client, server)]: + # generate all the keys + system(f"{rosenpass} gen-keys --public-key {name}-pqpk --secret-key {name}-pqsk") - with subtest("Set up rosenpass"): - for machine in [server, client]: - machine.succeed("systemctl start rosenpass@rp0.service") + # copy private keys to our side + machine.copy_from_host(f"{name}-pqsk", "/etc/rosenpass/rp0/pqsk") + machine.copy_from_host(f"{name}-pqpk", "/etc/rosenpass/rp0/pqpk") - for machine in [server, client]: - machine.wait_for_unit("rosenpass@rp0.service") + # copy public keys to other side + remote.copy_from_host(f"{name}-pqpk", f"/etc/rosenpass/rp0/peers/{name}/pqpk") + + machine.copy_from_host(f"${config}/{name}", "/etc/rosenpass/rp0.toml") + + for machine in [server, client]: + machine.wait_for_unit("wireguard-rp0.service") + + with subtest("wg network test"): + client.succeed("wg show all preshared-keys | grep none", timeout=5); + client.succeed("ping -c5 ${server.wg.ip4}") + server.succeed("ping -c5 ${client.wg.ip6}") + + with subtest("Set up rosenpass"): + for machine in [server, client]: + machine.succeed("systemctl start rosenpass@rp0.service") + + for machine in [server, client]: + machine.wait_for_unit("rosenpass@rp0.service") - with subtest("compare preshared keys"): - client.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); - server.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); + with subtest("compare preshared keys"): + client.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); + server.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); - def get_psk(m): - psk = m.succeed("wg show rp0 preshared-keys | awk '{print $2}'") - psk = psk.strip() - assert len(psk.split()) == 1, "Only one PSK" - return psk + def get_psk(m): + psk = m.succeed("wg show rp0 preshared-keys | awk '{print $2}'") + psk = psk.strip() + assert len(psk.split()) == 1, "Only one PSK" + return psk - assert get_psk(client) == get_psk(server), "preshared keys need to match" + assert get_psk(client) == get_psk(server), "preshared keys need to match" - with subtest("rosenpass network test"): - client.succeed("ping -c5 ${server.wg.ip4}") - server.succeed("ping -c5 ${client.wg.ip6}") - ''; + with subtest("rosenpass network test"): + client.succeed("ping -c5 ${server.wg.ip4}") + server.succeed("ping -c5 ${client.wg.ip6}") + ''; } diff --git a/tests/systemd/rp.nix b/tests/systemd/rp.nix index 7218d155..c0acdb8a 100644 --- a/tests/systemd/rp.nix +++ b/tests/systemd/rp.nix @@ -24,27 +24,31 @@ let verbose = true; dev = "test-rp-device0"; ip = "fc00::1/64"; - peers = [{ - public_keys_dir = "/etc/rosenpass/test-rp-device0/peers/client"; - allowed_ips = "fc00::2"; - }]; + peers = [ + { + public_keys_dir = "/etc/rosenpass/test-rp-device0/peers/client"; + allowed_ips = "fc00::2"; + } + ]; }; client_config = { private_keys_dir = "/run/credentials/rp@test-rp-device0.service"; verbose = true; dev = "test-rp-device0"; ip = "fc00::2/128"; - peers = [{ - public_keys_dir = "/etc/rosenpass/test-rp-device0/peers/server"; - endpoint = "${server.ip4}:9999"; - allowed_ips = "fc00::/64"; - }]; + peers = [ + { + public_keys_dir = "/etc/rosenpass/test-rp-device0/peers/server"; + endpoint = "${server.ip4}:9999"; + allowed_ips = "fc00::/64"; + } + ]; }; config = pkgs.runCommand "config" { } '' mkdir -pv $out - cp -v ${(pkgs.formats.toml {}).generate "test-rp-device0.toml" server_config} $out/server - cp -v ${(pkgs.formats.toml {}).generate "test-rp-device0.toml" client_config} $out/client + cp -v ${(pkgs.formats.toml { }).generate "test-rp-device0.toml" server_config} $out/server + cp -v ${(pkgs.formats.toml { }).generate "test-rp-device0.toml" client_config} $out/client ''; in { @@ -52,88 +56,105 @@ in nodes = let - shared = peer: { config, modulesPath, pkgs, ... }: { - # Need to work around a problem in recent systemd changes. - # It won't be necessary in other distros (for which the systemd file was designed), this is NixOS specific - # https://github.com/NixOS/nixpkgs/issues/258371#issuecomment-1925672767 - # This can potentially be removed in future nixpkgs updates - systemd.packages = [ - (pkgs.runCommand "rp@.service" { } '' - mkdir -p $out/lib/systemd/system - < ${pkgs.rosenpass}/lib/systemd/system/rosenpass.target > $out/lib/systemd/system/rosenpass.target - < ${pkgs.rosenpass}/lib/systemd/system/rp@.service \ - sed 's@^\(\[Service]\)$@\1\nEnvironment=PATH=${pkgs.iproute2}/bin:${pkgs.wireguard-tools}/bin@' | - sed 's@^ExecStartPre=envsubst @ExecStartPre='"${pkgs.envsubst}"'/bin/envsubst @' | - sed 's@^ExecStart=rp @ExecStart='"${pkgs.rosenpass}"'/bin/rp @' > $out/lib/systemd/system/rp@.service - '') - ]; - environment.systemPackages = [ pkgs.wireguard-tools ]; - networking.interfaces.eth1 = { - ipv4.addresses = [{ - address = peer.ip4; - prefixLength = 24; - }]; - ipv6.addresses = [{ - address = peer.ip6; - prefixLength = 64; - }]; + shared = + peer: + { + config, + modulesPath, + pkgs, + ... + }: + { + # Need to work around a problem in recent systemd changes. + # It won't be necessary in other distros (for which the systemd file was designed), this is NixOS specific + # https://github.com/NixOS/nixpkgs/issues/258371#issuecomment-1925672767 + # This can potentially be removed in future nixpkgs updates + systemd.packages = [ + (pkgs.runCommand "rp@.service" { } '' + mkdir -p $out/lib/systemd/system + < ${pkgs.rosenpass}/lib/systemd/system/rosenpass.target > $out/lib/systemd/system/rosenpass.target + < ${pkgs.rosenpass}/lib/systemd/system/rp@.service \ + sed 's@^\(\[Service]\)$@\1\nEnvironment=PATH=${pkgs.iproute2}/bin:${pkgs.wireguard-tools}/bin@' | + sed 's@^ExecStartPre=envsubst @ExecStartPre='"${pkgs.envsubst}"'/bin/envsubst @' | + sed 's@^ExecStart=rp @ExecStart='"${pkgs.rosenpass}"'/bin/rp @' > $out/lib/systemd/system/rp@.service + '') + ]; + environment.systemPackages = [ pkgs.wireguard-tools ]; + networking.interfaces.eth1 = { + ipv4.addresses = [ + { + address = peer.ip4; + prefixLength = 24; + } + ]; + ipv6.addresses = [ + { + address = peer.ip6; + prefixLength = 64; + } + ]; + }; }; - }; in { server = { imports = [ (shared server) ]; - networking.firewall.allowedUDPPorts = [ 9999 server.wg.listen ]; + networking.firewall.allowedUDPPorts = [ + 9999 + server.wg.listen + ]; }; client = { imports = [ (shared client) ]; }; }; - testScript = { ... }: '' - from os import system - rp = "${pkgs.rosenpass}/bin/rp" + testScript = + { ... }: + '' + from os import system + rp = "${pkgs.rosenpass}/bin/rp" - start_all() - - for machine in [server, client]: - machine.wait_for_unit("multi-user.target") - machine.wait_for_unit("network-online.target") - - with subtest("Key, Config, and Service Setup"): - for name, machine, remote in [("server", server, client), ("client", client, server)]: - # create all the keys - system(f"{rp} genkey {name}-sk") - system(f"{rp} pubkey {name}-sk {name}-pk") - - # copy secret keys to our side - for file in ["pqpk", "pqsk", "wgsk"]: - machine.copy_from_host(f"{name}-sk/{file}", f"/etc/rosenpass/test-rp-device0/{file}") - # copy public keys to other side - for file in ["pqpk", "wgpk"]: - remote.copy_from_host(f"{name}-pk/{file}", f"/etc/rosenpass/test-rp-device0/peers/{name}/{file}") - - machine.copy_from_host(f"${config}/{name}", "/etc/rosenpass/test-rp-device0.toml") + start_all() for machine in [server, client]: - machine.succeed("systemctl start rp@test-rp-device0.service") + machine.wait_for_unit("multi-user.target") + machine.wait_for_unit("network-online.target") - for machine in [server, client]: - machine.wait_for_unit("rp@test-rp-device0.service") + with subtest("Key, Config, and Service Setup"): + for name, machine, remote in [("server", server, client), ("client", client, server)]: + # create all the keys + system(f"{rp} genkey {name}-sk") + system(f"{rp} pubkey {name}-sk {name}-pk") - with subtest("compare preshared keys"): - client.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); - server.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); + # copy secret keys to our side + for file in ["pqpk", "pqsk", "wgsk"]: + machine.copy_from_host(f"{name}-sk/{file}", f"/etc/rosenpass/test-rp-device0/{file}") + # copy public keys to other side + for file in ["pqpk", "wgpk"]: + remote.copy_from_host(f"{name}-pk/{file}", f"/etc/rosenpass/test-rp-device0/peers/{name}/{file}") - def get_psk(m): - psk = m.succeed("wg show test-rp-device0 preshared-keys | awk '{print $2}'") - psk = psk.strip() - assert len(psk.split()) == 1, "Only one PSK" - return psk + machine.copy_from_host(f"${config}/{name}", "/etc/rosenpass/test-rp-device0.toml") - assert get_psk(client) == get_psk(server), "preshared keys need to match" + for machine in [server, client]: + machine.succeed("systemctl start rp@test-rp-device0.service") - with subtest("network test"): - client.succeed("ping -c5 ${server.wg.ip6}") - server.succeed("ping -c5 ${client.wg.ip6}") - ''; + for machine in [server, client]: + machine.wait_for_unit("rp@test-rp-device0.service") + + with subtest("compare preshared keys"): + client.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); + server.wait_until_succeeds("wg show all preshared-keys | grep --invert-match none", timeout=5); + + def get_psk(m): + psk = m.succeed("wg show test-rp-device0 preshared-keys | awk '{print $2}'") + psk = psk.strip() + assert len(psk.split()) == 1, "Only one PSK" + return psk + + assert get_psk(client) == get_psk(server), "preshared keys need to match" + + with subtest("network test"): + client.succeed("ping -c5 ${server.wg.ip6}") + server.succeed("ping -c5 ${client.wg.ip6}") + ''; } diff --git a/to/Cargo.toml b/to/Cargo.toml index bda13f3a..69712723 100644 --- a/to/Cargo.toml +++ b/to/Cargo.toml @@ -8,6 +8,7 @@ description = "Flexible destination parameters" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [dev-dependencies] doc-comment = { workspace = true } diff --git a/treefmt.nix b/treefmt.nix new file mode 100644 index 00000000..49e6c733 --- /dev/null +++ b/treefmt.nix @@ -0,0 +1,28 @@ +{ pkgs, ... }: +{ + # Used to find the project root + projectRootFile = "flake.nix"; + programs.nixfmt.enable = true; + programs.prettier = { + enable = true; + includes = [ + "*.css" + "*.html" + "*.js" + "*.json" + "*.json5" + "*.md" + "*.mdx" + "*.toml" + "*.yaml" + "*.yml" + ]; + excludes = [ "supply-chain/*" ]; + settings = { + plugins = [ + "${pkgs.nodePackages.prettier-plugin-toml}/lib/node_modules/prettier-plugin-toml/lib/index.js" + ]; + }; + }; + programs.rustfmt.enable = true; +} diff --git a/util/Cargo.toml b/util/Cargo.toml index d6bdf003..bdd1ddf6 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -8,6 +8,7 @@ description = "Rosenpass internal utilities" homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -23,7 +24,8 @@ thiserror = { workspace = true } mio = { workspace = true } tempfile = { workspace = true } uds = { workspace = true, optional = true, features = ["mio_1xx"] } - +libcrux-test-utils = { workspace = true, optional = true } [features] experiment_file_descriptor_passing = ["uds"] +trace_bench = ["dep:libcrux-test-utils"] diff --git a/util/src/fd.rs b/util/src/fd.rs index f6966e92..351d011c 100644 --- a/util/src/fd.rs +++ b/util/src/fd.rs @@ -521,13 +521,13 @@ mod tests { use std::io::{Read, Write}; #[test] - #[should_panic(expected = "fd != u32::MAX as RawFd")] + #[should_panic] fn test_claim_fd_invalid_neg() { let _ = claim_fd(-1); } #[test] - #[should_panic(expected = "fd != u32::MAX as RawFd")] + #[should_panic] fn test_claim_fd_invalid_max() { let _ = claim_fd(i64::MAX as RawFd); } @@ -561,7 +561,7 @@ mod tests { let mut file = FdIo(open_nullfd()?); let mut buf = [0; 10]; assert!(matches!(file.read(&mut buf), Ok(0) | Err(_))); - assert!(matches!(file.write(&buf), Err(_))); + assert!(file.write(&buf).is_err()); Ok(()) } diff --git a/util/src/length_prefix_encoding/encoder.rs b/util/src/length_prefix_encoding/encoder.rs index 1d3071e1..1e0c6d1f 100644 --- a/util/src/length_prefix_encoding/encoder.rs +++ b/util/src/length_prefix_encoding/encoder.rs @@ -618,7 +618,7 @@ mod tests { #[test] fn test_lpe_error_conversion_downcast_invalid() { let pos_error = PositionOutOfBufferBounds; - let sanity_error = SanityError::PositionOutOfBufferBounds(pos_error.into()); + let sanity_error = SanityError::PositionOutOfBufferBounds(pos_error); match MessageLenSanityError::try_from(sanity_error) { Ok(_) => panic!("Conversion should always fail (incompatible enum variant)"), Err(err) => assert!(matches!(err, PositionOutOfBufferBounds)), diff --git a/util/src/lib.rs b/util/src/lib.rs index 66d2387f..7949a3b7 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -30,6 +30,9 @@ pub mod option; pub mod result; /// Time and duration utilities. pub mod time; +/// Trace benchmarking utilities +#[cfg(feature = "trace_bench")] +pub mod trace_bench; /// Type-level numbers and arithmetic. pub mod typenum; /// Zero-copy serialization utilities. diff --git a/util/src/mem.rs b/util/src/mem.rs index f3f45f57..5d43f079 100644 --- a/util/src/mem.rs +++ b/util/src/mem.rs @@ -302,6 +302,6 @@ mod test_forgetting { drop_was_called.store(false, SeqCst); let forgetting = Forgetting::new(SetFlagOnDrop(drop_was_called.clone())); drop(forgetting); - assert_eq!(drop_was_called.load(SeqCst), false); + assert!(!drop_was_called.load(SeqCst)); } } diff --git a/util/src/time.rs b/util/src/time.rs index 0aabeff2..8e190470 100644 --- a/util/src/time.rs +++ b/util/src/time.rs @@ -13,7 +13,7 @@ use std::time::Instant; /// /// let timebase = Timebase::default(); /// let now = timebase.now(); -/// assert!(now > 0.0); +/// assert!(now >= 0.0); /// ``` #[derive(Clone, Debug)] @@ -39,13 +39,6 @@ mod tests { use std::thread::sleep; use std::time::Duration; - #[test] - fn test_timebase() { - let timebase = Timebase::default(); - let now = timebase.now(); - assert!(now > 0.0); - } - #[test] fn test_timebase_clone() { let timebase = Timebase::default(); diff --git a/util/src/trace_bench.rs b/util/src/trace_bench.rs new file mode 100644 index 00000000..367efa61 --- /dev/null +++ b/util/src/trace_bench.rs @@ -0,0 +1,23 @@ +use std::sync::OnceLock; +use std::time::Instant; + +use libcrux_test_utils::tracing; + +/// The trace value used in all Rosepass crates. +static TRACE: OnceLock = OnceLock::new(); + +/// The trace type used to trace Rosenpass for performance measurement. +pub type RpTrace = tracing::MutexTrace<&'static str, Instant>; + +/// The trace event type used to trace Rosenpass for performance measurement. +pub type RpEventType = tracing::TraceEvent<&'static str, Instant>; + +// Re-export to make functionality available and callers don't need to also directly depend on +// [`libcrux_test_utils`]. +pub use libcrux_test_utils::tracing::trace_span; +pub use tracing::Trace; + +/// Returns a reference to the trace and lazily initializes it. +pub fn trace() -> &'static tracing::MutexTrace<&'static str, Instant> { + TRACE.get_or_init(tracing::MutexTrace::default) +} diff --git a/wireguard-broker/Cargo.toml b/wireguard-broker/Cargo.toml index ae987f73..e43585c1 100644 --- a/wireguard-broker/Cargo.toml +++ b/wireguard-broker/Cargo.toml @@ -8,6 +8,7 @@ description = "Rosenpass internal broker that runs as root and supplies exchange homepage = "https://rosenpass.eu/" repository = "https://github.com/rosenpass/rosenpass" readme = "readme.md" +rust-version = "1.77.0" [dependencies] thiserror = { workspace = true } @@ -19,7 +20,7 @@ wireguard-uapi = { workspace = true } # Socket handler only rosenpass-to = { workspace = true } -tokio = { version = "1.42.0", features = ["sync", "full", "mio"] } +tokio = { workspace = true, features = ["sync", "full", "mio"] } anyhow = { workspace = true } clap = { workspace = true } env_logger = { workspace = true } @@ -28,8 +29,8 @@ derive_builder = { workspace = true } postcard = { workspace = true } # Problem in CI, unknown reasons: dependency (libc) specified without providing a local path, Git repository, version, or workspace dependency to use # Maybe something about the combination of features and optional crates? -rustix = { version = "0.38.42", optional = true } -libc = { version = "0.2", optional = true } +rustix = { workspace = true, optional = true } +libc = { workspace = true, optional = true } # Mio broker client mio = { workspace = true }