From f1a68173a46045fdb7f9cf7bea6f7877169e258a Mon Sep 17 00:00:00 2001 From: 0xd6cb6d73 <72226198+0xd6cb6d73@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:48:44 +0100 Subject: [PATCH] Add a crypto provider template Payload_Type/crypto_provider is a starting point for a Mythic crypto provider: a consuming container of type crypto that implements an agent's cryptographic protocol. It is a complete Go service with no cryptography in it. - internal/service registers with Mythic as a crypto container, consumes its _crypto_provider_rpc queue, checks each request's mythic-auth-context and handles requests concurrently. - internal/provider has one hook for each of prepare_profile, begin_session, open and seal. Each rejects requests until it is implemented. - internal/storage is a client for Mythic's storage RPC: load, commit and get_result. - internal/wirecheck checks messages against the rules and limits of Mythic's crypto provider API; the SDK declares only the types. - internal/transport adapts the MythicContainer SDK's RabbitMQ connection. go.mod points MythicContainer at the fork with the crypto provider types until they are released. The template's README covers running, installing and agent integration, and the repository README links it. Co-authored-by: Codex Co-Authored-By: Claude Mythos 5.2 Co-Authored-By: Claude Opus 5.5 --- Payload_Type/crypto_provider/.dockerignore | 5 + Payload_Type/crypto_provider/.env.example | 10 + Payload_Type/crypto_provider/.gitignore | 4 + Payload_Type/crypto_provider/Dockerfile | 18 + Payload_Type/crypto_provider/Makefile | 10 + Payload_Type/crypto_provider/NOTICE | 10 + Payload_Type/crypto_provider/README.md | 85 +++++ Payload_Type/crypto_provider/go.mod | 35 ++ Payload_Type/crypto_provider/go.sum | 103 ++++++ .../internal/provider/provider.go | 88 +++++ .../internal/provider/provider_test.go | 108 ++++++ .../internal/service/config.go | 59 ++++ .../internal/service/config_test.go | 87 +++++ .../internal/service/service.go | 194 +++++++++++ .../internal/service/service_test.go | 201 +++++++++++ .../internal/storage/client.go | 200 +++++++++++ .../internal/storage/client_test.go | 249 +++++++++++++ .../internal/transport/amqp.go | 327 ++++++++++++++++++ .../internal/transport/concurrent.go | 165 +++++++++ .../internal/wirecheck/storage.go | 167 +++++++++ .../internal/wirecheck/wirecheck.go | 180 ++++++++++ .../internal/wirecheck/wirecheck_test.go | 231 +++++++++++++ Payload_Type/crypto_provider/main.go | 33 ++ README.md | 4 + 24 files changed, 2573 insertions(+) create mode 100644 Payload_Type/crypto_provider/.dockerignore create mode 100644 Payload_Type/crypto_provider/.env.example create mode 100644 Payload_Type/crypto_provider/.gitignore create mode 100644 Payload_Type/crypto_provider/Dockerfile create mode 100644 Payload_Type/crypto_provider/Makefile create mode 100644 Payload_Type/crypto_provider/NOTICE create mode 100644 Payload_Type/crypto_provider/README.md create mode 100644 Payload_Type/crypto_provider/go.mod create mode 100644 Payload_Type/crypto_provider/go.sum create mode 100644 Payload_Type/crypto_provider/internal/provider/provider.go create mode 100644 Payload_Type/crypto_provider/internal/provider/provider_test.go create mode 100644 Payload_Type/crypto_provider/internal/service/config.go create mode 100644 Payload_Type/crypto_provider/internal/service/config_test.go create mode 100644 Payload_Type/crypto_provider/internal/service/service.go create mode 100644 Payload_Type/crypto_provider/internal/service/service_test.go create mode 100644 Payload_Type/crypto_provider/internal/storage/client.go create mode 100644 Payload_Type/crypto_provider/internal/storage/client_test.go create mode 100644 Payload_Type/crypto_provider/internal/transport/amqp.go create mode 100644 Payload_Type/crypto_provider/internal/transport/concurrent.go create mode 100644 Payload_Type/crypto_provider/internal/wirecheck/storage.go create mode 100644 Payload_Type/crypto_provider/internal/wirecheck/wirecheck.go create mode 100644 Payload_Type/crypto_provider/internal/wirecheck/wirecheck_test.go create mode 100644 Payload_Type/crypto_provider/main.go diff --git a/Payload_Type/crypto_provider/.dockerignore b/Payload_Type/crypto_provider/.dockerignore new file mode 100644 index 0000000..be7bd22 --- /dev/null +++ b/Payload_Type/crypto_provider/.dockerignore @@ -0,0 +1,5 @@ +.build +.git +.env +.env.* +!.env.example diff --git a/Payload_Type/crypto_provider/.env.example b/Payload_Type/crypto_provider/.env.example new file mode 100644 index 0000000..ad3608d --- /dev/null +++ b/Payload_Type/crypto_provider/.env.example @@ -0,0 +1,10 @@ +# Mythic supplies these settings to installed service containers. +RABBITMQ_HOST=mythic_rabbitmq +RABBITMQ_PORT=5672 +RABBITMQ_USER=mythic_user +RABBITMQ_PASSWORD= +RABBITMQ_VHOST=mythic_vhost +# RABBITMQ_URL may replace the individual connection settings. +# RABBITMQ_URL=amqp://user:password@127.0.0.1:5672/mythic_vhost +EXAMPLE_CRYPTO_PROVIDER_NAME=example_crypto +EXAMPLE_CRYPTO_RPC_TIMEOUT=20s diff --git a/Payload_Type/crypto_provider/.gitignore b/Payload_Type/crypto_provider/.gitignore new file mode 100644 index 0000000..d7d1068 --- /dev/null +++ b/Payload_Type/crypto_provider/.gitignore @@ -0,0 +1,4 @@ +.build/ +.env +.env.* +!.env.example diff --git a/Payload_Type/crypto_provider/Dockerfile b/Payload_Type/crypto_provider/Dockerfile new file mode 100644 index 0000000..b0d9223 --- /dev/null +++ b/Payload_Type/crypto_provider/Dockerfile @@ -0,0 +1,18 @@ +FROM golang:1.27.2-bookworm AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -buildvcs=false -trimpath -o /out/crypto-provider . + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install --yes --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* \ + && touch /usr/local/bin/.env \ + && chmod 0444 /usr/local/bin/.env \ + && useradd --system --uid 65532 --no-create-home --shell /usr/sbin/nologin provider +COPY --from=build /out/crypto-provider /usr/local/bin/crypto-provider +COPY NOTICE /usr/share/doc/crypto-provider/NOTICE +WORKDIR /Mythic +USER 65532:65532 +ENTRYPOINT ["/usr/local/bin/crypto-provider"] diff --git a/Payload_Type/crypto_provider/Makefile b/Payload_Type/crypto_provider/Makefile new file mode 100644 index 0000000..6a99eff --- /dev/null +++ b/Payload_Type/crypto_provider/Makefile @@ -0,0 +1,10 @@ +.PHONY: build test run + +build: + CGO_ENABLED=0 go build -buildvcs=false -trimpath -o .build/crypto-provider . + +test: + go test -race ./... + +run: build + .build/crypto-provider diff --git a/Payload_Type/crypto_provider/NOTICE b/Payload_Type/crypto_provider/NOTICE new file mode 100644 index 0000000..6fd8f69 --- /dev/null +++ b/Payload_Type/crypto_provider/NOTICE @@ -0,0 +1,10 @@ +The transport, service, storage, and wire-check scaffolding originated in +mythic-beaconcrypt under the following BSD Zero Clause terms: + +BSD Zero Clause License + +Copyright (C) 2026 by 0xd6cb6d73 72226198+0xd6cb6d73@users.noreply.github.com + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/Payload_Type/crypto_provider/README.md b/Payload_Type/crypto_provider/README.md new file mode 100644 index 0000000..5076b9a --- /dev/null +++ b/Payload_Type/crypto_provider/README.md @@ -0,0 +1,85 @@ +# Crypto provider skeleton + +This standalone Go service shows the Mythic crypto-provider API without a particular cryptographic implementation. It registers `example_crypto`, advertises the `example` scheme and explicitly rejects the four protocol methods with `not_implemented`. Replace `internal/provider` with your implementation before building an agent that selects it. + +This example requires [Mythic's crypto-provider API v1](https://github.com/0xd6cb6d73/Mythic/blob/crypto-shim/mythic-docker/src/crypto/provider/README.md). The pinned MythicContainer SDK supplies RabbitMQ transport and request authorization, but does not yet have a crypto service registration API. The small adapter here supplies that lifecycle; it does not register a payload type or C2 profile. + +## Files to keep and files to replace + +| Path | Purpose | +| --- | --- | +| `main.go` | Load provider configuration, connect the backend to the service, and stop on SIGTERM. | +| `internal/provider` | Replace this package with your protocol, agent configuration, key handling, state ownership and limits. | +| `internal/service` | Shared configuration, registration, authorization checks and process lifecycle. | +| `internal/transport` | SDK adapter, exclusive queues, bounded concurrent RPC and reply handling. | +| `internal/storage` | Authenticated client for Mythic's optional opaque state store. | +| `internal/wirecheck` | Checks API messages and storage requests against the rules and limits in Mythic's API document. | + +The SDK package `github.com/MythicMeta/MythicContainer/cryptoproviderstructs`, imported as `wire`, supplies the API v1 message types, method names, failure outcomes and routing key. It does not validate messages: `internal/wirecheck` holds this service's checks and limits, which follow Mythic's API document. Mythic still validates every message itself. + +The generic files are also used by `mythic-beaconcrypt`; its provider package adapts the Beaconcrypt engine behind the same `service.Backend` interface. Cryptographic algorithms, native libraries and their build dependencies belong in the replaceable provider package and its Docker build. + +## Run and install + +Run `make test` for the native-free tests, or `make build` to build the service. For a local broker, export `RABBITMQ_URL` or the connection settings shown in `.env.example`, then run `make run`. The SDK also reads an `.env` file beside the executable. The Dockerfile pre-creates that file and runs the binary as an unprivileged user. + +To install only this example, stage a small service repository. From the `ExampleContainers` checkout: + +```sh +install_root=$(mktemp -d) +mkdir -p "$install_root/Payload_Type" +cp -R Payload_Type/crypto_provider "$install_root/Payload_Type/crypto_provider" +cat > "$install_root/config.json" <<'JSON' +{ + "exclude_payload_type": false, + "exclude_c2_profiles": true, + "exclude_documentation_payload": true, + "exclude_documentation_c2": true, + "exclude_documentation_wrapper": true, + "exclude_agent_icons": true +} +JSON +/path/to/Mythic/mythic-cli install folder "$install_root" +rm -rf "$install_root" +``` + +The installer copies the service before the temporary directory is removed. Installing the entire ExampleContainers repository installs its other examples too. For your own repository, keep this `config.json` and `Payload_Type//` layout, and use `mythic-cli install github `. + +Mythic supplies the `RABBITMQ_*` settings to installed containers. `EXAMPLE_CRYPTO_PROVIDER_NAME` defaults to `example_crypto`; `EXAMPLE_CRYPTO_RPC_TIMEOUT` defaults to `20s`. The pinned SDK supports `amqp` URLs. Restart the container after changing connection configuration. + +## Required provider lifecycle + +`service.Run` starts exclusive provider, resync and startup queues before announcing the service with `consuming_container_sync`. Registration includes `type: crypto`, a version and capabilities; the business route is `_crypto_provider_rpc`. The resync queue re-announces the same definition. Startup notifications do not supply a credential to retain, and constructing a backend does not read or write state. + +Every business request carries the transient Mythic authorization context in both its RabbitMQ header and JSON body. The service checks that they agree before calling the backend. Preserve the supplied `context.Context` for every storage RPC, echo `auth_context`, `request_id` and `operation_scope_id` in responses, and never persist or log the authorization context. It changes between attempts and is excluded from request digests. + +The SDK owns the connection and outgoing RPC correlation. The adapter processes a bounded number of business requests concurrently so one operation cannot block all other operations. It terminates the worker after connection loss or an uncertain transport timeout; let the container supervisor start a fresh process. + +## Implementing the protocol + +`internal/provider.Provider.Handle` is the dispatch point: + +| Method | Required implementation | +| --- | --- | +| `prepare_profile` | Create or restore a provider profile and return an opaque profile reference and agent configuration. | +| `begin_session` | Authenticate the agent's initial message and routing claims, establish a session, and return its reply and opaque session identity. | +| `open` | Authenticate and decrypt one incoming message within the selected operation and session. | +| `seal` | Encrypt and authenticate one outgoing message within that session. | + +Validate every request before processing. Honor the advertised size limit and result-retention interval, and preserve the operation scope when looking up profiles, sessions and request IDs. Keep cryptographic formats opaque to Mythic. A `rejected` failure promises there is no unresolved cryptographic effect; after an ambiguous stateful effect, return `unresolved`. Mythic retries with the same request ID; answer that retry from the saved result instead of repeating the work. Capabilities are sent once, in the registration message; there is no method that asks for them again. + +This skeleton advertises `volatile` session persistence because it has no durable implementation. It creates no profiles or sessions and does not claim usable encryption. A real implementation must provide repeatable outcomes for repeated request IDs, reject reuse with changed inputs, and decide whether session state survives a worker restart. Advertise `durable` only when that promise is implemented. + +The optional `storage.Store` passed to `provider.New` stores opaque provider state and exact operation results through Mythic RPC. It has three methods. `Load` reads one row. `Commit` changes any number of rows in one namespace atomically: it lists expectations (a row at a revision, or absent), the rows to write, and optionally the request's result. `LookupResult` (`get_result`) returns the result saved for a request ID and digest. For a durable implementation, scope state keys to the Mythic operation, call `LookupResult` before doing any work, and commit the state change and its result together, expecting the revisions you read. A `precondition_failed` commit applied nothing: another writer changed a row, so read again and repeat the step. Keep every row bounded; storage has no method that deletes one. Storage `request_id` values identify transport calls; the immutable operation request ID and input digest identify the cryptographic effect. State access must use the current authenticated request context, so the example performs no storage calls at startup. Mythic's API document describes stateless, single-snapshot and per-session-row layouts. + +## Agent-side integration + +Installing this service supplies the server half of a protocol. The agent needs its own matching implementation and compile-time configuration. Use the qualified selection `provider::`; for this skeleton that is `provider:example_crypto:example`. Return only the agent configuration your protocol needs from `prepare_profile`. + +The payload container must advertise `supported_crypto_schemes: ["example"]` in its payload-type sync definition. These are bare scheme names, independent of the provider worker's registered name. Mythic passes the profile's opaque `agent_config` bytes to the builder as the base64 string `provider_config`; decode it before parsing the provider-specific configuration, and embed it for the selected C2 profile. + +For an agent with a provider registry, add the provider's session implementation, register its scheme, and connect its target-specific build preparation and configuration parsing. Profiles should use the shared crypto session interface rather than compare the provider name to a particular library. Do not add Beaconcrypt dependencies or checks to a different provider's agent plumbing. + +## License + +The original scaffold is available under the BSD Zero Clause terms reproduced in `NOTICE`. Keep this notice when copying the example into a new repository. diff --git a/Payload_Type/crypto_provider/go.mod b/Payload_Type/crypto_provider/go.mod new file mode 100644 index 0000000..9ea6fef --- /dev/null +++ b/Payload_Type/crypto_provider/go.mod @@ -0,0 +1,35 @@ +module github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider + +go 1.26.0 + +require ( + github.com/MythicMeta/MythicContainer v1.7.0-rc5 + github.com/google/uuid v1.6.0 + github.com/rabbitmq/amqp091-go v1.14.0 +) + +require ( + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/rs/zerolog v1.34.0 // indirect + github.com/sagikazarmark/locafero v0.12.0 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/spf13/viper v1.21.0 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/grpc v1.83.1 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect +) + +replace github.com/MythicMeta/MythicContainer => github.com/0xd6cb6d73/MythicContainer v1.7.0-rc5.0.20261204124904-4cc80093d035 diff --git a/Payload_Type/crypto_provider/go.sum b/Payload_Type/crypto_provider/go.sum new file mode 100644 index 0000000..340d86b --- /dev/null +++ b/Payload_Type/crypto_provider/go.sum @@ -0,0 +1,103 @@ +github.com/0xd6cb6d73/MythicContainer v1.7.0-rc5.0.20261204124904-4cc80093d035 h1:AUOrwnaIygttPlg8saynSRlRvq+RfV3VFSp4zHnbRQo= +github.com/0xd6cb6d73/MythicContainer v1.7.0-rc5.0.20261204124904-4cc80093d035/go.mod h1:bHB40wZf9txJKNc2x5H5g+3CJ2NCJlT9t5zCZBbVXYE= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek= +github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY= +github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ= +github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= +github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y= +google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/Payload_Type/crypto_provider/internal/provider/provider.go b/Payload_Type/crypto_provider/internal/provider/provider.go new file mode 100644 index 0000000..61c3b91 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/provider/provider.go @@ -0,0 +1,88 @@ +// Package provider is the replaceable part of this example. Add your protocol, +// configuration and state management here; keep the Mythic adapter separate. +package provider + +import ( + "context" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/service" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/storage" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" +) + +type Config struct { + Service service.Config +} + +func LoadConfig() (Config, error) { + config, err := service.LoadConfig("example_crypto", "EXAMPLE_CRYPTO") + if err != nil { + return Config{}, err + } + config.Description = "Crypto provider skeleton; protocol methods are not implemented" + config.Version = "0.0.1" + config.Capabilities = wire.Capabilities{ + APIVersion: wire.APIVersion, Schemes: []string{"example"}, Establishment: "single_round", + SessionPersistence: "volatile", MaxMessageBytes: 1 << 20, ResultRetentionSeconds: 300, + } + return Config{Service: config}, nil +} + +type Provider struct{} + +// New receives the client for Mythic's opaque state store. This skeleton does +// not use it: construction must not read or write state, because storage is +// authorized only by a request's context. A durable provider can retain the +// store and pass each request's context to its load, commit and get_result calls. +func New(config Config, _ storage.Store) (service.Backend, error) { + if err := wirecheck.Capabilities(config.Service.Capabilities); err != nil { + return nil, err + } + return &Provider{}, nil +} + +func (p *Provider) Close() {} + +func (p *Provider) Handle(_ context.Context, request wire.Request) wire.Response { + response := wire.Response{ + APIVersion: wire.APIVersion, RequestID: request.RequestID, + OperationScopeID: request.OperationScopeID, AuthContext: request.AuthContext, + } + if err := wirecheck.Request(request); err != nil { + response.Error = &wire.Failure{Code: "invalid_input", Message: err.Error(), Outcome: wire.OutcomeRejected} + return response + } + // A durable implementation of every method first calls get_result with the + // request ID and its own digest of the request (excluding auth_context). It + // returns a saved result unchanged and fails a reused ID with other input. + switch request.Method { + case wire.PrepareProfile: + // TODO: Validate scheme and provider_json. Return profile_ref and opaque + // agent_config, and bind the profile to operation_scope_id. Return the + // namespace and state_id that later requests for this profile should carry. + case wire.BeginSession: + // TODO: Authenticate the initial message and the payload_uuid/next_uuid + // claims against this operation's profile. Return session_ref, namespace, + // optional state_id, and the nonempty establishment reply in message. + // The reply must give the agent next_uuid. Commit the session's state and + // the exact result together before returning. + case wire.Open: + // TODO: Verify that the session belongs to this operation, then open the + // authenticated packet and return plaintext in message. Commit the state + // change and the result together, so a retry does not advance receive + // state twice. Reject an oversized or unauthentic packet as rejected. + case wire.Seal: + // TODO: Verify that the session belongs to this operation, then seal and + // return ciphertext in message. Commit the state change and the result + // together; a repeated request_id must return the same bytes without + // encrypting again. Keep the session usable if a sealed reply is never + // delivered. + } + // Every unfinished method rejects before changing any cryptographic state. + response.Error = &wire.Failure{ + Code: "not_implemented", Message: "implement this protocol method in internal/provider", + Outcome: wire.OutcomeRejected, + } + return response +} diff --git a/Payload_Type/crypto_provider/internal/provider/provider_test.go b/Payload_Type/crypto_provider/internal/provider/provider_test.go new file mode 100644 index 0000000..1858ccf --- /dev/null +++ b/Payload_Type/crypto_provider/internal/provider/provider_test.go @@ -0,0 +1,108 @@ +package provider + +import ( + "context" + "slices" + "testing" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/service" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" + "github.com/google/uuid" +) + +func testConfig(t *testing.T) Config { + t.Helper() + t.Setenv("RABBITMQ_URL", "amqp://test:password@127.0.0.1:5672/mythic_vhost") + t.Setenv("EXAMPLE_CRYPTO_PROVIDER_NAME", "") + t.Setenv("EXAMPLE_CRYPTO_RPC_TIMEOUT", "") + config, err := LoadConfig() + if err != nil { + t.Fatal(err) + } + return config +} + +func testProvider(t *testing.T) service.Backend { + t.Helper() + // A volatile implementation need not use the optional durable state store. + backend, err := New(testConfig(t), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(backend.Close) + return backend +} + +func requestFor(method string) wire.Request { + return wire.Request{ + APIVersion: wire.APIVersion, RequestID: uuid.NewString(), OperationScopeID: 7, + Method: method, Scheme: "example", ProfileRef: "profile", SessionRef: "session", + Namespace: "operation-7", StateID: "state", Message: []byte("initial-message"), + PayloadUUID: uuid.NewString(), NextUUID: uuid.NewString(), + AuthContext: "mctx_this-request-only", + } +} + +func assertIdentity(t *testing.T, request wire.Request, response wire.Response) { + t.Helper() + if response.APIVersion != wire.APIVersion || response.RequestID != request.RequestID || response.OperationScopeID != request.OperationScopeID || response.AuthContext != request.AuthContext { + t.Fatal("provider lost API version, request identity, operation scope, or transient authorization") + } +} + +func TestRegisteredCapabilitiesAreValidAndVolatile(t *testing.T) { + capabilities := testConfig(t).Service.Capabilities + if err := wirecheck.Capabilities(capabilities); err != nil { + t.Fatal(err) + } + if !slices.Equal(capabilities.Schemes, []string{"example"}) || capabilities.SessionPersistence != "volatile" { + t.Fatalf("unexpected capabilities: %#v", capabilities) + } +} + +func TestNewRejectsInvalidCapabilities(t *testing.T) { + config := testConfig(t) + config.Service.Capabilities.Schemes = nil + if _, err := New(config, nil); err == nil { + t.Fatal("provider accepted capabilities without a scheme") + } +} + +func TestProtocolStubsRejectBeforeAnyCryptographicEffect(t *testing.T) { + backend := testProvider(t) + for _, method := range []string{wire.PrepareProfile, wire.BeginSession, wire.Open, wire.Seal} { + t.Run(method, func(t *testing.T) { + request := requestFor(method) + if err := wirecheck.Request(request); err != nil { + t.Fatal(err) + } + response := backend.Handle(context.Background(), request) + assertIdentity(t, request, response) + if response.Success || response.Error == nil || response.Error.Code != "not_implemented" || response.Error.Outcome != wire.OutcomeRejected { + t.Fatalf("stub was accepted or reported an ambiguous effect: %#v", response) + } + if response.ProfileRef != "" || response.SessionRef != "" || len(response.Message) != 0 || len(response.AgentConfig) != 0 { + t.Fatal("stub manufactured protocol output") + } + }) + } +} + +func TestInvalidRequestsAreRejectedBeforeDispatch(t *testing.T) { + backend := testProvider(t) + for _, change := range []func(*wire.Request){ + func(r *wire.Request) { r.APIVersion++ }, + func(r *wire.Request) { r.RequestID = "invalid" }, + func(r *wire.Request) { r.OperationScopeID = 0 }, + func(r *wire.Request) { r.Method = "unknown" }, + } { + request := requestFor(wire.PrepareProfile) + change(&request) + response := backend.Handle(context.Background(), request) + assertIdentity(t, request, response) + if response.Success || response.Error == nil || response.Error.Code != "invalid_input" || response.Error.Outcome != wire.OutcomeRejected { + t.Fatalf("invalid input was accepted: %#v", response) + } + } +} diff --git a/Payload_Type/crypto_provider/internal/service/config.go b/Payload_Type/crypto_provider/internal/service/config.go new file mode 100644 index 0000000..65a98a7 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/service/config.go @@ -0,0 +1,59 @@ +package service + +import ( + "errors" + "fmt" + "net" + "net/url" + "os" + "time" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" +) + +type Config struct { + Name string + AMQPURL string + RPCTimeout time.Duration + Description string + Version string + Capabilities wire.Capabilities +} + +// LoadConfig reads transport settings shared by crypto providers. Protocol +// configuration, metadata, and capabilities belong to the provider package. +func LoadConfig(defaultName, envPrefix string) (Config, error) { + name := env(envPrefix+"_PROVIDER_NAME", defaultName) + if wirecheck.Name(name) != nil { + return Config{}, fmt.Errorf("invalid %s_PROVIDER_NAME", envPrefix) + } + address := os.Getenv("RABBITMQ_URL") + if address == "" { + password := os.Getenv("RABBITMQ_PASSWORD") + if password == "" { + return Config{}, errors.New("RABBITMQ_PASSWORD or RABBITMQ_URL is required") + } + u := url.URL{Scheme: "amqp", Host: net.JoinHostPort(env("RABBITMQ_HOST", "mythic_rabbitmq"), env("RABBITMQ_PORT", "5672")), Path: "/" + env("RABBITMQ_VHOST", "mythic_vhost"), User: url.UserPassword(env("RABBITMQ_USER", "mythic_user"), password)} + address = u.String() + } + u, err := url.Parse(address) + if err == nil && u.Scheme == "amqps" { + return Config{}, errors.New("the pinned MythicContainer SDK does not support AMQPS") + } + if err != nil || u.Scheme != "amqp" || u.Hostname() == "" { + return Config{}, errors.New("invalid RABBITMQ_URL") + } + timeout, err := time.ParseDuration(env(envPrefix+"_RPC_TIMEOUT", "20s")) + if err != nil || timeout < time.Second || timeout > 30*time.Second { + return Config{}, fmt.Errorf("%s_RPC_TIMEOUT must be between 1s and 30s", envPrefix) + } + return Config{Name: name, AMQPURL: address, RPCTimeout: timeout}, nil +} + +func env(name, fallback string) string { + if value := os.Getenv(name); value != "" { + return value + } + return fallback +} diff --git a/Payload_Type/crypto_provider/internal/service/config_test.go b/Payload_Type/crypto_provider/internal/service/config_test.go new file mode 100644 index 0000000..a9b2136 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/service/config_test.go @@ -0,0 +1,87 @@ +package service + +import ( + "net/url" + "strings" + "testing" + "time" +) + +func configEnvironment(t *testing.T) { + t.Helper() + for _, name := range []string{"EXAMPLE_PROVIDER_NAME", "EXAMPLE_RPC_TIMEOUT", "OTHER_PROVIDER_NAME", "OTHER_RPC_TIMEOUT", "RABBITMQ_URL", "RABBITMQ_HOST", "RABBITMQ_PORT", "RABBITMQ_USER", "RABBITMQ_PASSWORD", "RABBITMQ_VHOST"} { + t.Setenv(name, "") + } + t.Setenv("RABBITMQ_URL", "amqp://test:password@127.0.0.1:5672/mythic_vhost") +} + +func TestLoadConfigDefaultsAndProviderPrefix(t *testing.T) { + configEnvironment(t) + t.Setenv("OTHER_PROVIDER_NAME", "unrelated") + t.Setenv("OTHER_RPC_TIMEOUT", "1s") + config, err := LoadConfig("example", "EXAMPLE") + if err != nil { + t.Fatal(err) + } + if config.Name != "example" || config.RPCTimeout != 20*time.Second || config.Description != "" || config.Version != "" || len(config.Capabilities.Schemes) != 0 { + t.Fatalf("transport defaults included provider-specific configuration: %#v", config) + } + t.Setenv("EXAMPLE_PROVIDER_NAME", "custom-provider") + t.Setenv("EXAMPLE_RPC_TIMEOUT", "3s") + config, err = LoadConfig("example", "EXAMPLE") + if err != nil || config.Name != "custom-provider" || config.RPCTimeout != 3*time.Second { + t.Fatalf("provider prefix was ignored: %#v, %v", config, err) + } +} + +func TestLoadConfigEscapesBrokerCredentialsAndVirtualHost(t *testing.T) { + configEnvironment(t) + t.Setenv("RABBITMQ_URL", "") + t.Setenv("RABBITMQ_HOST", "::1") + t.Setenv("RABBITMQ_PORT", "5673") + t.Setenv("RABBITMQ_USER", "provider@mythic") + t.Setenv("RABBITMQ_PASSWORD", "p@ss:/?#%word") + t.Setenv("RABBITMQ_VHOST", "test space") + config, err := LoadConfig("example", "EXAMPLE") + if err != nil { + t.Fatal(err) + } + parsed, err := url.Parse(config.AMQPURL) + if err != nil { + t.Fatal(err) + } + password, _ := parsed.User.Password() + if parsed.Hostname() != "::1" || parsed.Port() != "5673" || parsed.User.Username() != "provider@mythic" || password != "p@ss:/?#%word" || parsed.Path != "/test space" { + t.Fatal("broker URL changed credentials, host, or virtual host") + } +} + +func TestLoadConfigRejectsInvalidInputWithoutDisclosingSecrets(t *testing.T) { + for _, test := range []struct{ name, value string }{ + {"EXAMPLE_PROVIDER_NAME", "bad:name"}, {"EXAMPLE_PROVIDER_NAME", "bad name"}, + {"RABBITMQ_URL", "amqps://user:secret@example.test"}, + {"RABBITMQ_URL", "https://user:secret@example.test"}, + {"RABBITMQ_URL", "amqp:///missing-host"}, + {"EXAMPLE_RPC_TIMEOUT", "999ms"}, {"EXAMPLE_RPC_TIMEOUT", "31s"}, {"EXAMPLE_RPC_TIMEOUT", "invalid"}, + } { + t.Run(test.name+"="+test.value, func(t *testing.T) { + configEnvironment(t) + t.Setenv(test.name, test.value) + _, err := LoadConfig("example", "EXAMPLE") + if err == nil { + t.Fatal("invalid configuration accepted") + } + if strings.Contains(err.Error(), "user:secret") { + t.Fatal("configuration error disclosed deployment credentials") + } + }) + } +} + +func TestLoadConfigRequiresBrokerCredentials(t *testing.T) { + configEnvironment(t) + t.Setenv("RABBITMQ_URL", "") + if _, err := LoadConfig("example", "EXAMPLE"); err == nil { + t.Fatal("missing broker credentials accepted") + } +} diff --git a/Payload_Type/crypto_provider/internal/service/service.go b/Payload_Type/crypto_provider/internal/service/service.go new file mode 100644 index 0000000..b54c7ab --- /dev/null +++ b/Payload_Type/crypto_provider/internal/service/service.go @@ -0,0 +1,194 @@ +// Package service adapts MythicContainer v4 lifecycle messages to the generic +// crypto-provider API. Protocol implementation and state ownership belong to +// the provider backend. +package service + +import ( + "context" + "encoding/json" + "errors" + "time" + + sdk "github.com/MythicMeta/MythicContainer/rabbitmq" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/storage" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/transport" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" +) + +const ( + ContainerVersion = "v1.5.0" + SyncRoute = "consuming_container_sync" +) + +type Processor interface { + Handle(context.Context, wire.Request) wire.Response +} + +// Backend owns protocol processing and its shutdown. Factories compose a +// backend without storage IO; state is loaded lazily under request authorization. +type Backend interface { + Processor + Close() +} + +type Factory func(storage.Store) (Backend, error) + +func syncMessage(config Config) ([]byte, error) { + if err := wirecheck.Name(config.Name); err != nil { + return nil, err + } + if err := wirecheck.Capabilities(config.Capabilities); err != nil { + return nil, err + } + return json.Marshal(map[string]any{ + "container_version": ContainerVersion, + "consuming_container": map[string]any{ + "name": config.Name, "type": "crypto", "description": config.Description, "semver": config.Version, + "subscriptions": []string{}, "crypto_capabilities": config.Capabilities, + }, + }) +} + +func Sync(ctx context.Context, caller transport.Caller, config Config) error { + body, err := syncMessage(config) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, config.RPCTimeout) + defer cancel() + reply, err := caller.Call(ctx, SyncRoute, body) + if err != nil { + return errors.New("mythic consuming-service sync failed") + } + var response struct { + Success bool `json:"success"` + } + if json.Unmarshal(reply, &response) != nil || !response.Success { + return errors.New("mythic rejected consuming-service sync") + } + return nil +} + +// NewHandler accepts ordinary Mythic JSON RPC with the SDK's transient +// authorization context. Storage calls inherit that same context; no service +// credential or startup token is retained. +func NewHandler(processor Processor, timeout time.Duration) transport.Handler { + return func(ctx context.Context, body []byte) ([]byte, error) { + if len(body) > transport.MaxBodyBytes { + return []byte(`{"success":false,"error":"crypto provider request exceeds limit"}`), nil + } + var request wire.Request + if json.Unmarshal(body, &request) != nil { + return []byte(`{"success":false,"error":"invalid crypto provider request"}`), nil + } + token, ok := sdk.AuthTokenFromContext(ctx) + if !ok || token == "" || request.AuthContext != token { + return []byte(`{"success":false,"error":"invalid crypto provider authorization context"}`), nil + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return json.Marshal(processor.Handle(ctx, request)) + } +} + +// Run acquires broker exclusivity before accepting protocol requests. Provider +// state is created or restored lazily by authenticated requests. A broker loss +// ends this process instance; its supervisor starts a fresh worker. +func Run(ctx context.Context, config Config, factory Factory) error { + if factory == nil { + return errors.New("crypto provider backend factory is required") + } + if _, err := syncMessage(config); err != nil { + return err + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + connectCtx, connectCancel := context.WithTimeout(ctx, config.RPCTimeout) + broker, err := transport.Connect(connectCtx, config.AMQPURL) + connectCancel() + if err != nil { + return errors.New("cannot connect to RabbitMQ") + } + defer func() { _ = broker.Close() }() + store, err := storage.New(broker, config.Name) + if err != nil { + return err + } + processor, err := factory(store) + if err != nil { + return err + } + if processor == nil { + return errors.New("crypto provider backend is required") + } + defer func() { + cancel() + processor.Close() + }() + ready := make(chan struct{}) + // syncMessage checked the name above. + route := wire.RoutingKey(config.Name) + providerHandler := NewHandler(processor, config.RPCTimeout) + cryptoErrors, err := broker.ConsumeConcurrentRPC(ctx, route, func(ctx context.Context, body []byte) ([]byte, error) { + select { + case <-ready: + return providerHandler(ctx, body) + case <-ctx.Done(): + return nil, ctx.Err() + } + }) + if err != nil { + return errors.New("cannot acquire exclusive provider queue") + } + resyncErrors, err := broker.ConsumeRPC(ctx, config.Name+"_consuming_container_rpc_resync", func(ctx context.Context, _ []byte) ([]byte, error) { + err := Sync(ctx, broker, config) + return json.Marshal(map[string]any{"success": err == nil}) + }) + if err != nil { + return errors.New("cannot start provider resync queue") + } + startErrors, err := broker.ConsumeDirect(ctx, config.Name+"_container_on_start", func(_ context.Context, _ []byte) ([]byte, error) { + // The operator token in this notification is intentionally not retained. + // Each business request supplies its own transient Mythic authorization. + return nil, nil + }) + if err != nil { + return errors.New("cannot start provider lifecycle queue") + } + startCtx, startCancel := context.WithTimeout(ctx, config.RPCTimeout) + err = broker.Start(startCtx) + startCancel() + if err != nil { + return errors.New("cannot start MythicContainer provider listeners") + } + if err = Sync(ctx, broker, config); err != nil { + return err + } + close(ready) + select { + case <-ctx.Done(): + return ctx.Err() + case brokerErr := <-broker.NotifyClose(): + if brokerErr != nil { + return errors.New("rabbitmq connection failed") + } + return errors.New("rabbitmq connection closed") + case consumerErr := <-cryptoErrors: + if consumerErr != nil { + return errors.New("crypto request consumer failed") + } + return errors.New("crypto request consumer stopped") + case consumerErr := <-resyncErrors: + if consumerErr != nil { + return errors.New("provider resync consumer failed") + } + return errors.New("provider resync consumer stopped") + case consumerErr := <-startErrors: + if consumerErr != nil { + return errors.New("provider lifecycle consumer failed") + } + return errors.New("provider lifecycle consumer stopped") + } +} diff --git a/Payload_Type/crypto_provider/internal/service/service_test.go b/Payload_Type/crypto_provider/internal/service/service_test.go new file mode 100644 index 0000000..0e395b2 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/service/service_test.go @@ -0,0 +1,201 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "testing" + "time" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/storage" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" + sdk "github.com/MythicMeta/MythicContainer/rabbitmq" + "github.com/google/uuid" +) + +type processorFunc func(context.Context, wire.Request) wire.Response + +func (f processorFunc) Handle(ctx context.Context, request wire.Request) wire.Response { + return f(ctx, request) +} + +type callerFunc func(context.Context, string, []byte) ([]byte, error) + +func (f callerFunc) Call(ctx context.Context, route string, body []byte) ([]byte, error) { + return f(ctx, route, body) +} + +func TestHandlerRejectsMalformedOrMissingAuthorizationBeforeProcessing(t *testing.T) { + for _, name := range []string{"malformed JSON", "missing header", "missing request context", "mismatched context"} { + t.Run(name, func(t *testing.T) { + ctx := sdk.NewContextWithAuthToken(context.Background(), "mctx_current-attempt") + request := wire.Request{APIVersion: wire.APIVersion, RequestID: uuid.NewString(), OperationScopeID: 17, Method: wire.PrepareProfile, Scheme: "example", AuthContext: "mctx_current-attempt"} + switch name { + case "missing header": + ctx = context.Background() + case "missing request context": + request.AuthContext = "" + case "mismatched context": + request.AuthContext = "mctx_other-attempt" + } + body, err := json.Marshal(request) + if err != nil { + t.Fatal(err) + } + if name == "malformed JSON" { + body = []byte("{") + } + calls := 0 + handler := NewHandler(processorFunc(func(context.Context, wire.Request) wire.Response { calls++; return wire.Response{} }), time.Second) + body, err = handler(ctx, body) + if err != nil || !json.Valid(body) || calls != 0 { + t.Fatalf("invalid input reached processor or stopped consumer: calls=%d response=%q err=%v", calls, body, err) + } + var result struct { + Success bool `json:"success"` + } + if err := json.Unmarshal(body, &result); err != nil || result.Success { + t.Fatalf("invalid input was accepted: %s %v", body, err) + } + }) + } +} + +func TestHandlerPreservesRequestScopeAndAuthorization(t *testing.T) { + for _, success := range []bool{true, false} { + t.Run(map[bool]string{true: "success", false: "failure"}[success], func(t *testing.T) { + request := wire.Request{APIVersion: wire.APIVersion, RequestID: uuid.NewString(), OperationScopeID: 17, Method: wire.PrepareProfile, Scheme: "example", AuthContext: "mctx_transient-attempt"} + payload, err := json.Marshal(request) + if err != nil { + t.Fatal(err) + } + calls := 0 + handler := NewHandler(processorFunc(func(ctx context.Context, got wire.Request) wire.Response { + calls++ + if !reflect.DeepEqual(got, request) { + t.Fatalf("request changed: %#v", got) + } + if token, ok := sdk.AuthTokenFromContext(ctx); !ok || token != request.AuthContext { + t.Fatal("processor lost transient SDK authorization") + } + deadline, ok := ctx.Deadline() + if !ok || time.Until(deadline) > time.Second { + t.Fatal("processor did not receive bounded request context") + } + response := wire.Response{APIVersion: wire.APIVersion, RequestID: got.RequestID, OperationScopeID: got.OperationScopeID, AuthContext: got.AuthContext, Success: success} + if success { + response.ProfileRef, response.ProviderJSON = "profile", json.RawMessage(`{"provider":"example"}`) + } else { + response.Error = &wire.Failure{Code: "invalid_input", Message: "request rejected", Outcome: wire.OutcomeRejected} + } + return response + }), time.Second) + ctx := sdk.NewContextWithAuthToken(context.Background(), request.AuthContext) + body, err := handler(ctx, payload) + if err != nil { + t.Fatal(err) + } + var response wire.Response + if err = json.Unmarshal(body, &response); err != nil { + t.Fatal(err) + } + if response.RequestID != request.RequestID || response.OperationScopeID != request.OperationScopeID || response.AuthContext != request.AuthContext || response.Success != success || calls != 1 { + t.Fatalf("response correlation changed: %#v, calls=%d", response, calls) + } + err = wirecheck.Response(response, request) + if success && err != nil { + t.Fatal(err) + } + if !success { + var failure *wire.Failure + if !errors.As(err, &failure) || failure.Code != "invalid_input" || failure.Outcome != wire.OutcomeRejected { + t.Fatalf("failure was not preserved: %v", err) + } + } + }) + } +} + +func TestSyncUsesV4ContainerWireAndConfiguredMetadata(t *testing.T) { + config := Config{Name: "custom-provider", Description: "Example provider", Version: "2.3.4", RPCTimeout: time.Second, Capabilities: wire.Capabilities{APIVersion: wire.APIVersion, Schemes: []string{"example", "other"}, Establishment: "single_round", SessionPersistence: "volatile", MaxMessageBytes: 12345, ResultRetentionSeconds: 67890}} + calls := 0 + caller := callerFunc(func(ctx context.Context, route string, body []byte) ([]byte, error) { + calls++ + if route != SyncRoute { + t.Fatalf("wrong sync route: %q", route) + } + if _, ok := ctx.Deadline(); !ok { + t.Fatal("sync has no deadline") + } + var message struct { + ContainerVersion string `json:"container_version"` + Container struct { + Name string `json:"name"` + Type string `json:"type"` + SemVer string `json:"semver"` + Description string `json:"description"` + Subscriptions []string `json:"subscriptions"` + Capabilities wire.Capabilities `json:"crypto_capabilities"` + } `json:"consuming_container"` + } + if err := json.Unmarshal(body, &message); err != nil { + t.Fatal(err) + } + if message.ContainerVersion != "v1.5.0" || message.Container.Name != config.Name || message.Container.Type != "crypto" || message.Container.SemVer != config.Version || message.Container.Description != config.Description || message.Container.Subscriptions == nil || len(message.Container.Subscriptions) != 0 { + t.Fatalf("invalid consuming-container sync: %s", body) + } + if !reflect.DeepEqual(message.Container.Capabilities, config.Capabilities) { + t.Fatalf("advertised capabilities differ from config: %#v vs %#v", message.Container.Capabilities, config.Capabilities) + } + if err := wirecheck.Capabilities(message.Container.Capabilities); err != nil { + t.Fatal(err) + } + return []byte(`{"success":true}`), nil + }) + if err := Sync(context.Background(), caller, config); err != nil { + t.Fatal(err) + } + if calls != 1 { + t.Fatalf("sync repeated %d times", calls) + } +} + +func TestSyncRejectsFailureWithoutRetry(t *testing.T) { + for _, reply := range []string{`{"success":false,"error":"unsupported container"}`, `not JSON`, `{}`} { + calls := 0 + err := Sync(context.Background(), callerFunc(func(context.Context, string, []byte) ([]byte, error) { calls++; return []byte(reply), nil }), Config{Name: "example", RPCTimeout: time.Second, Capabilities: wire.Capabilities{APIVersion: wire.APIVersion, Schemes: []string{"example"}, Establishment: "single_round", SessionPersistence: "volatile", MaxMessageBytes: 1024, ResultRetentionSeconds: wirecheck.MinResultRetentionSeconds}}) + if err == nil || calls != 1 { + t.Fatalf("failed sync accepted or repeated: %v calls=%d", err, calls) + } + } +} + +func TestSyncRejectsInvalidAdvertisementBeforePublishing(t *testing.T) { + valid := Config{Name: "example", RPCTimeout: time.Second, Capabilities: wire.Capabilities{APIVersion: wire.APIVersion, Schemes: []string{"example"}, Establishment: "single_round", SessionPersistence: "volatile", MaxMessageBytes: 1024, ResultRetentionSeconds: wirecheck.MinResultRetentionSeconds}} + for _, change := range []func(*Config){ + func(config *Config) { config.Name = "bad:name" }, + func(config *Config) { config.Capabilities.APIVersion = 0 }, + func(config *Config) { config.Capabilities.SessionPersistence = "unknown" }, + } { + config := valid + change(&config) + calls := 0 + err := Sync(context.Background(), callerFunc(func(context.Context, string, []byte) ([]byte, error) { calls++; return []byte(`{"success":true}`), nil }), config) + if err == nil || calls != 0 { + t.Fatalf("invalid advertisement reached Mythic: error=%v calls=%d", err, calls) + } + } +} + +func TestRunRejectsInvalidCompositionBeforeConnecting(t *testing.T) { + if err := Run(context.Background(), Config{}, nil); err == nil { + t.Fatal("missing backend factory accepted") + } + called := false + err := Run(context.Background(), Config{Name: "example"}, func(storage.Store) (Backend, error) { called = true; return nil, nil }) + if err == nil || called { + t.Fatalf("invalid capabilities reached backend factory: error=%v called=%v", err, called) + } +} diff --git a/Payload_Type/crypto_provider/internal/storage/client.go b/Payload_Type/crypto_provider/internal/storage/client.go new file mode 100644 index 0000000..7555e4a --- /dev/null +++ b/Payload_Type/crypto_provider/internal/storage/client.go @@ -0,0 +1,200 @@ +// Package storage is the authenticated client for Mythic's generic opaque +// provider store. It never imports the Mythic server or opens its database. +package storage + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/transport" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" + "github.com/google/uuid" +) + +const Route = "mythic_rpc_crypto_provider_storage" + +// Store is Mythic's storage RPC: load one row, commit an atomic multi-row +// change with an optional result, and look up a saved result. +type Store interface { + Load(context.Context, wire.StateKey) (wire.StoredState, error) + Commit(context.Context, wire.CommitRequest) (wire.CommitResult, error) + LookupResult(context.Context, wire.LookupResultRequest) (wire.OperationResult, error) +} + +// ErrUnauthorized marks Mythic's refusal of the request's authorization context. +var ErrUnauthorized = errors.New("crypto storage authorization refused") + +type Client struct { + caller transport.Caller + name string +} + +func New(caller transport.Caller, name string) (*Client, error) { + if caller == nil || name == "" { + return nil, errors.New("invalid crypto storage client configuration") + } + if err := wirecheck.Name(name); err != nil { + return nil, err + } + return &Client{caller: caller, name: name}, nil +} + +type request struct { + APIVersion int `json:"api_version"` + RequestID string `json:"request_id"` + ProviderName string `json:"provider_name"` + Method string `json:"method"` + Input json.RawMessage `json:"input"` +} + +type response struct { + APIVersion int `json:"api_version"` + RequestID string `json:"request_id"` + ProviderName string `json:"provider_name"` + Success bool `json:"success"` + Result json.RawMessage `json:"result,omitempty"` + Error *wire.StorageFailure `json:"error,omitempty"` +} + +// call invokes the SDK with a fresh RPC request ID and the caller's transient +// Mythic authorization context. Publish retries use the same JSON bytes; the +// SDK does not retry a response timeout. The immutable commit/get_result input +// ID is independent of this ID. Mismatched, malformed, or lost replies remain +// uncertain outcomes rather than trusted storage failures. +func (c *Client) call(ctx context.Context, method string, input, output any) error { + data, err := json.Marshal(input) + if err != nil { + return fmt.Errorf("encode crypto storage input: %w", err) + } + req := request{APIVersion: wire.APIVersion, RequestID: uuid.NewString(), ProviderName: c.name, Method: method, Input: data} + payload, err := json.Marshal(req) + if err != nil { + return err + } + reply, err := c.caller.Call(ctx, Route, payload) + if err != nil { + return fmt.Errorf("crypto storage %s outcome is uncertain: %w", method, err) + } + if len(reply) > transport.MaxBodyBytes { + return errors.New("crypto storage response exceeds limit") + } + var result response + if err := json.Unmarshal(reply, &result); err != nil { + return fmt.Errorf("invalid crypto storage response: %w", err) + } + if result.APIVersion != wire.APIVersion || result.RequestID != req.RequestID || result.ProviderName != c.name { + return errors.New("mismatched crypto storage response") + } + if !result.Success { + if result.Error == nil || result.Error.Code == "" || len(result.Result) != 0 { + return errors.New("invalid crypto storage failure") + } + return storageError(result.Error) + } + if result.Error != nil || len(result.Result) == 0 || string(result.Result) == "null" { + return errors.New("invalid crypto storage success") + } + if err := json.Unmarshal(result.Result, output); err != nil { + return fmt.Errorf("decode crypto storage result: %w", err) + } + return nil +} + +func storageError(failure *wire.StorageFailure) error { + var sentinel error + switch failure.Code { + case wire.StorageInvalidInput: + sentinel = wirecheck.ErrInvalidInput + case wire.StorageNotFound: + sentinel = wirecheck.ErrNotFound + case wire.StoragePreconditionFailed: + if failure.StateID == "" { + return errors.New("crypto storage precondition failure names no row") + } + return &wirecheck.PreconditionError{StateID: failure.StateID} + case wire.StorageRequestConflict: + sentinel = wirecheck.ErrRequestConflict + case wire.StorageUnauthorized: + sentinel = ErrUnauthorized + } + if sentinel != nil { + return fmt.Errorf("%w: %s", sentinel, failure.Message) + } + return failure +} + +func (c *Client) Load(ctx context.Context, input wire.StateKey) (wire.StoredState, error) { + var output wire.StoredState + if err := wirecheck.StateKey(input); err != nil { + return output, err + } + err := c.call(ctx, "load", input, &output) + if err == nil && (output.StateKey != input || output.Revision < 1 || len(output.StateBlob) > wirecheck.MaxStateBlobBytes || + len(output.ProviderJSON) > wirecheck.MaxProviderJSONBytes || !json.Valid(output.ProviderJSON)) { + err = errors.New("invalid crypto storage state") + } + return output, err +} + +// Commit validates the request before sending it, so an invalid request is a +// definite failure, and checks that a reply matches the request it answers. +func (c *Client) Commit(ctx context.Context, input wire.CommitRequest) (wire.CommitResult, error) { + var output wire.CommitResult + if err := wirecheck.Commit(input); err != nil { + return output, err + } + if err := c.call(ctx, "commit", input, &output); err != nil { + return output, err + } + if err := ValidateCommitResult(input, output); err != nil { + return wire.CommitResult{}, err + } + return output, nil +} + +// ValidateCommitResult checks that a commit reply can answer its request: a +// result exactly when one was sent, and for an applied commit one revision per +// write that follows each expectation. +func ValidateCommitResult(input wire.CommitRequest, output wire.CommitResult) error { + invalid := errors.New("invalid crypto storage commit result") + if (input.Result != nil) != (len(output.Result) != 0) || len(output.Result) > wirecheck.MaxResultBytes || len(output.Result) != 0 && !json.Valid(output.Result) { + return invalid + } + if output.Cached { + if input.Result == nil || len(output.Revisions) != 0 { + return invalid + } + return nil + } + if len(output.Revisions) != len(input.Writes) { + return invalid + } + expected := make(map[string]wire.Expectation, len(input.Expect)) + for _, e := range input.Expect { + expected[e.StateID] = e + } + for i, revision := range output.Revisions { + if revision.StateID != input.Writes[i].StateID || revision.Revision < 1 { + return invalid + } + if e, ok := expected[revision.StateID]; ok && (e.Absent && revision.Revision != 1 || !e.Absent && revision.Revision != e.Revision+1) { + return invalid + } + } + return nil +} + +func (c *Client) LookupResult(ctx context.Context, input wire.LookupResultRequest) (wire.OperationResult, error) { + var output wire.OperationResult + if err := wirecheck.LookupResult(input); err != nil { + return output, err + } + err := c.call(ctx, "get_result", input, &output) + if err == nil && (output.StateKey != input.StateKey || output.RequestID != input.RequestID || output.InputDigest != input.InputDigest || output.Revision < 1 || len(output.Result) == 0 || len(output.Result) > wirecheck.MaxResultBytes || !json.Valid(output.Result)) { + err = errors.New("mismatched crypto storage operation result") + } + return output, err +} diff --git a/Payload_Type/crypto_provider/internal/storage/client_test.go b/Payload_Type/crypto_provider/internal/storage/client_test.go new file mode 100644 index 0000000..ededa4f --- /dev/null +++ b/Payload_Type/crypto_provider/internal/storage/client_test.go @@ -0,0 +1,249 @@ +package storage + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/wirecheck" + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" + sdk "github.com/MythicMeta/MythicContainer/rabbitmq" +) + +type callerFunc func(context.Context, string, []byte) ([]byte, error) + +func (f callerFunc) Call(ctx context.Context, route string, body []byte) ([]byte, error) { + return f(ctx, route, body) +} + +func responseBytes(t *testing.T, response response) []byte { + t.Helper() + body, err := json.Marshal(response) + if err != nil { + t.Fatal(err) + } + return body +} + +func decodeRequest(t *testing.T, route string, body []byte) request { + t.Helper() + if route != Route { + t.Fatalf("wrong storage route: %q", route) + } + var req request + if err := json.Unmarshal(body, &req); err != nil { + t.Fatal(err) + } + if req.APIVersion != wire.APIVersion || req.RequestID == "" || req.ProviderName != "example_crypto" { + t.Fatalf("invalid storage request: %#v", req) + } + return req +} + +func newTestClient(t *testing.T, call callerFunc) *Client { + t.Helper() + client, err := New(call, "example_crypto") + if err != nil { + t.Fatal(err) + } + return client +} + +func TestStorageClientTypedMethodsAndBinaryState(t *testing.T) { + key := wire.StateKey{Namespace: "server", StateID: "owner-1"} + blob := []byte{0, 255, 128, 1, 0} + digest := strings.Repeat("a", 64) + commit := wire.CommitRequest{Namespace: key.Namespace, + Expect: []wire.Expectation{{StateID: key.StateID, Revision: 4}, {StateID: "marker", Revision: 2}, {StateID: "new", Absent: true}}, + Writes: []wire.StateWrite{{StateID: key.StateID, StateBlob: blob}, {StateID: "new", StateBlob: []byte{}}}, + Result: &wire.ResultRecord{StateID: key.StateID, RequestID: "immutable-id", InputDigest: digest, Result: json.RawMessage(`{"message":"AP8="}`)}} + seen := map[string]bool{} + client := newTestClient(t, func(_ context.Context, route string, body []byte) ([]byte, error) { + req := decodeRequest(t, route, body) + if seen[req.RequestID] { + t.Fatal("outer storage request ID was reused") + } + seen[req.RequestID] = true + var result any + switch req.Method { + case "load": + result = wire.StoredState{StateKey: key, StateBlob: blob, ProviderJSON: json.RawMessage(`{}`), Revision: 4} + case "commit": + var input wire.CommitRequest + if err := json.Unmarshal(req.Input, &input); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(input, commit) { + t.Fatalf("commit input changed: %+v", input) + } + result = wire.CommitResult{Revisions: []wire.RowRevision{{StateID: key.StateID, Revision: 5}, {StateID: "new", Revision: 1}}, Result: input.Result.Result} + case "get_result": + result = wire.OperationResult{StateKey: key, RequestID: "immutable-id", InputDigest: digest, Revision: 5, Result: json.RawMessage(`{"message":"AP8="}`)} + default: + t.Fatalf("unexpected method %q", req.Method) + } + encoded, err := json.Marshal(result) + if err != nil { + t.Fatal(err) + } + return responseBytes(t, response{APIVersion: wire.APIVersion, RequestID: req.RequestID, ProviderName: req.ProviderName, Success: true, Result: encoded}), nil + }) + loaded, err := client.Load(context.Background(), key) + if err != nil || string(loaded.StateBlob) != string(blob) || loaded.Revision != 4 { + t.Fatalf("load: %#v %v", loaded, err) + } + if committed, err := client.Commit(context.Background(), commit); err != nil || committed.Revisions[1].Revision != 1 { + t.Fatalf("commit: %+v %v", committed, err) + } + if _, err = client.LookupResult(context.Background(), wire.LookupResultRequest{StateKey: key, RequestID: "immutable-id", InputDigest: digest}); err != nil { + t.Fatal(err) + } + if len(seen) != 3 { + t.Fatalf("expected three calls, got %d", len(seen)) + } +} + +// A commit reply must answer the request: a result exactly when one was sent, +// and one revision per write that follows its expectation. +func TestStorageClientRejectsCommitRepliesThatDoNotMatch(t *testing.T) { + commit := wire.CommitRequest{Namespace: "ns", Expect: []wire.Expectation{{StateID: "a", Revision: 3}, {StateID: "b", Absent: true}}, + Writes: []wire.StateWrite{{StateID: "a"}, {StateID: "b"}}, + Result: &wire.ResultRecord{StateID: "a", RequestID: "r", InputDigest: strings.Repeat("a", 64), Result: json.RawMessage(`{}`)}} + valid := wire.CommitResult{Revisions: []wire.RowRevision{{StateID: "a", Revision: 4}, {StateID: "b", Revision: 1}}, Result: json.RawMessage(`{}`)} + if err := ValidateCommitResult(commit, valid); err != nil { + t.Fatal(err) + } + if err := ValidateCommitResult(commit, wire.CommitResult{Revisions: []wire.RowRevision{}, Result: json.RawMessage(`{"saved":1}`), Cached: true}); err != nil { + t.Fatalf("cached reply: %v", err) + } + for name, mutate := range map[string]func(*wire.CommitResult){ + "missing result": func(r *wire.CommitResult) { r.Result = nil }, + "missing revision": func(r *wire.CommitResult) { r.Revisions = r.Revisions[:1] }, + "wrong order": func(r *wire.CommitResult) { r.Revisions[0], r.Revisions[1] = r.Revisions[1], r.Revisions[0] }, + "skipped revision": func(r *wire.CommitResult) { r.Revisions[0].Revision = 5 }, + "created at two": func(r *wire.CommitResult) { r.Revisions[1].Revision = 2 }, + "cached with rows": func(r *wire.CommitResult) { r.Cached = true }, + "invalid result": func(r *wire.CommitResult) { r.Result = json.RawMessage(`{`) }, + } { + t.Run(name, func(t *testing.T) { + reply := valid + reply.Revisions = append([]wire.RowRevision(nil), valid.Revisions...) + mutate(&reply) + if err := ValidateCommitResult(commit, reply); err == nil { + t.Fatal("mismatched commit reply accepted") + } + }) + } + withoutResult := commit + withoutResult.Result = nil + if err := ValidateCommitResult(withoutResult, valid); err == nil { + t.Fatal("result accepted for a commit that sent none") + } +} + +func TestStorageClientRejectsInvalidRequestsBeforeSending(t *testing.T) { + client := newTestClient(t, func(context.Context, string, []byte) ([]byte, error) { + t.Fatal("invalid request was sent") + return nil, nil + }) + if _, err := client.Commit(context.Background(), wire.CommitRequest{Namespace: "ns"}); !errors.Is(err, wirecheck.ErrInvalidInput) { + t.Fatalf("empty commit: %v", err) + } + if _, err := client.Load(context.Background(), wire.StateKey{Namespace: "ns", StateID: "bad id"}); !errors.Is(err, wirecheck.ErrInvalidInput) { + t.Fatalf("invalid key: %v", err) + } +} + +func TestStorageClientRejectsMalformedOrMismatchedReplies(t *testing.T) { + for _, name := range []string{"missing correlation", "malformed JSON", "request id", "provider name", "api version", "contradiction", "missing result", "wrong state", "zero revision"} { + t.Run(name, func(t *testing.T) { + client := newTestClient(t, func(_ context.Context, route string, body []byte) ([]byte, error) { + req := decodeRequest(t, route, body) + res := response{APIVersion: wire.APIVersion, RequestID: req.RequestID, ProviderName: req.ProviderName, Success: true, Result: json.RawMessage(`{"namespace":"server","state_id":"owner-1","state_blob":"AA==","provider_json":{},"revision":1}`)} + switch name { + case "missing correlation": + return []byte(`{"success":false,"error":"unauthorized"}`), nil + case "request id": + res.RequestID = "another-request" + case "provider name": + res.ProviderName = "another-provider" + case "api version": + res.APIVersion++ + case "contradiction": + res.Error = &wire.StorageFailure{Code: "not_found"} + case "missing result": + res.Result = nil + case "wrong state": + res.Result = json.RawMessage(`{"namespace":"other","state_id":"owner-1","state_blob":"AA==","provider_json":{},"revision":1}`) + case "zero revision": + res.Result = json.RawMessage(`{"namespace":"server","state_id":"owner-1","state_blob":"AA==","provider_json":{},"revision":0}`) + } + reply := responseBytes(t, res) + if name == "malformed JSON" { + reply = []byte("{") + } + return reply, nil + }) + if _, err := client.Load(context.Background(), wire.StateKey{Namespace: "server", StateID: "owner-1"}); err == nil { + t.Fatal("accepted invalid reply") + } + }) + } +} + +func TestStorageClientMapsCorrelatedFailures(t *testing.T) { + for code, sentinel := range map[string]error{"not_found": wirecheck.ErrNotFound, "precondition_failed": wirecheck.ErrPreconditionFailed, "request_conflict": wirecheck.ErrRequestConflict, "invalid_input": wirecheck.ErrInvalidInput, "unauthorized": ErrUnauthorized} { + t.Run(code, func(t *testing.T) { + client := newTestClient(t, func(_ context.Context, route string, body []byte) ([]byte, error) { + req := decodeRequest(t, route, body) + return responseBytes(t, response{APIVersion: wire.APIVersion, RequestID: req.RequestID, ProviderName: req.ProviderName, Error: &wire.StorageFailure{Code: code, Message: "trusted failure", StateID: "marker"}}), nil + }) + _, err := client.Load(context.Background(), wire.StateKey{Namespace: "ns", StateID: "row"}) + if !errors.Is(err, sentinel) { + t.Fatalf("wrong error: %v", err) + } + var precondition *wirecheck.PreconditionError + if code == "precondition_failed" && (!errors.As(err, &precondition) || precondition.StateID != "marker") { + t.Fatalf("precondition failure lost its row: %v", err) + } + }) + } + client := newTestClient(t, func(_ context.Context, route string, body []byte) ([]byte, error) { + req := decodeRequest(t, route, body) + return responseBytes(t, response{APIVersion: wire.APIVersion, RequestID: req.RequestID, ProviderName: req.ProviderName, Error: &wire.StorageFailure{Code: "precondition_failed"}}), nil + }) + if _, err := client.Load(context.Background(), wire.StateKey{Namespace: "ns", StateID: "row"}); err == nil || errors.Is(err, wirecheck.ErrPreconditionFailed) { + t.Fatalf("precondition failure without a row was trusted: %v", err) + } +} + +func TestStorageClientNeverAutomaticallyRetriesUncertainCommit(t *testing.T) { + calls := 0 + lost := errors.New("response lost after commit") + client := newTestClient(t, func(context.Context, string, []byte) ([]byte, error) { calls++; return nil, lost }) + _, err := client.Commit(context.Background(), wire.CommitRequest{Namespace: "ns", Writes: []wire.StateWrite{{StateID: "a"}}}) + if calls != 1 || !errors.Is(err, lost) || errors.Is(err, wirecheck.ErrNotFound) { + t.Fatalf("uncertain commit was trusted or retried: %d %v", calls, err) + } +} + +func TestStorageClientForwardsTransientSDKAuthorization(t *testing.T) { + const token = "mctx_campaign-request" + client := newTestClient(t, func(ctx context.Context, route string, body []byte) ([]byte, error) { + if got, ok := sdk.AuthTokenFromContext(ctx); !ok || got != token { + t.Fatal("storage call lost caller authorization context") + } + if strings.Contains(string(body), token) { + t.Fatal("storage body retained transient authorization") + } + req := decodeRequest(t, route, body) + return responseBytes(t, response{APIVersion: wire.APIVersion, RequestID: req.RequestID, ProviderName: req.ProviderName, Error: &wire.StorageFailure{Code: "not_found"}}), nil + }) + _, err := client.Load(sdk.NewContextWithAuthToken(context.Background(), token), wire.StateKey{Namespace: "ns", StateID: "row"}) + if !errors.Is(err, wirecheck.ErrNotFound) { + t.Fatalf("unexpected storage failure: %v", err) + } +} diff --git a/Payload_Type/crypto_provider/internal/transport/amqp.go b/Payload_Type/crypto_provider/internal/transport/amqp.go new file mode 100644 index 0000000..e91ba87 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/transport/amqp.go @@ -0,0 +1,327 @@ +// Package transport adapts the MythicContainer SDK's custom queue and RPC APIs. +// The SDK owns connections, lifecycle consumers and outbound RPC correlation. +// Business RPC delivery is bounded and concurrent on the SDK-owned connection. +package transport + +import ( + "context" + "encoding/json" + "errors" + "net/url" + "strings" + "sync" + "time" + + sdkconfig "github.com/MythicMeta/MythicContainer/config" + sdk "github.com/MythicMeta/MythicContainer/rabbitmq" + amqp "github.com/rabbitmq/amqp091-go" +) + +const ( + Exchange = "mythic_exchange" + MaxBodyBytes = 192 << 20 + operationTimeout = 30 * time.Second +) + +type Handler func(context.Context, []byte) ([]byte, error) +type Caller interface { + Call(context.Context, string, []byte) ([]byte, error) +} + +type sdkConnection interface { + CloseDeadline(time.Time) error + NotifyClose(chan *amqp.Error) chan *amqp.Error +} + +type sdkHooks struct { + initialize func() + start func() + connection func() (sdkConnection, error) + channel func() (*amqp.Channel, error) + addRPC func(sdk.RPCQueueStruct) + addDirect func(sdk.DirectQueueStruct) + call func(context.Context, string, string, []byte, bool, ...sdk.RPCRetryPolicy) ([]byte, error) + publish func(context.Context, string, string, string, []byte, bool) error +} + +// Broker is one process's SDK adapter. Register every queue before Start. The +// SDK is a process-global singleton: an adapter is never restarted or reused +// after an uncertain transport outcome. The process supervisor starts a fresh +// worker, which obtains exclusive queues before acquiring a durable owner. +type Broker struct { + mu sync.Mutex + hooks sdkHooks + conn sdkConnection + started bool + terminal error + closed chan *amqp.Error + done chan struct{} + concurrent []concurrentRPC +} + +var sdkProcessClaim struct { + sync.Mutex + claimed bool +} + +func Connect(ctx context.Context, address string) (*Broker, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + sdkProcessClaim.Lock() + defer sdkProcessClaim.Unlock() + if sdkProcessClaim.claimed { + return nil, errors.New("MythicContainer SDK permits one worker adapter per process") + } + if err := configureSDK(address); err != nil { + return nil, err + } + sdkProcessClaim.claimed = true + return newBroker(sdkHooks{ + initialize: sdk.Initialize, + start: func() { sdk.StartServices([]string{}) }, + connection: func() (sdkConnection, error) { return sdk.RabbitMQConnection.GetConnection() }, + channel: func() (*amqp.Channel, error) { + conn, err := sdk.RabbitMQConnection.GetConnection() + if err != nil { + return nil, err + } + return conn.Channel() + }, + addRPC: sdk.RabbitMQConnection.AddRPCQueue, + addDirect: sdk.RabbitMQConnection.AddDirectQueue, + call: sdk.RabbitMQConnection.SendRPCMessageWithContext, + publish: sdk.RabbitMQConnection.SendMessageWithContext, + }), nil +} + +func newBroker(hooks sdkHooks) *Broker { + return &Broker{hooks: hooks, closed: make(chan *amqp.Error, 1), done: make(chan struct{})} +} + +func configureSDK(address string) error { + uri, err := amqp.ParseURI(address) + if err != nil || uri.Host == "" { + return errors.New("invalid RabbitMQ SDK address") + } + if uri.Scheme != "amqp" { + return errors.New("this MythicContainer SDK supports amqp URLs only") + } + // SDK GetConnection interpolates these fields into a URL. Encode them once + // so credentials and virtual hosts with reserved characters remain exact. + credentials := strings.SplitN(url.UserPassword(uri.Username, uri.Password).String(), ":", 2) + if len(credentials) != 2 { + return errors.New("invalid RabbitMQ SDK credentials") + } + host := uri.Host + if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") { + host = "[" + host + "]" + } + sdkconfig.MythicConfig.RabbitmqHost = host + sdkconfig.MythicConfig.RabbitmqPort = uint(uri.Port) + sdkconfig.MythicConfig.RabbitmqUser = credentials[0] + sdkconfig.MythicConfig.RabbitmqPassword = credentials[1] + sdkconfig.MythicConfig.RabbitmqVHost = url.PathEscape(uri.Vhost) + sdkconfig.MythicConfig.CustomRPCTimeout = operationTimeout + return nil +} + +// Start uses the SDK's documented lower-level startup API. Custom queue +// registrations are started even with an empty built-in-services list. Unlike +// StartAndRunForever(nil), this API does not terminate for the empty list. +func (b *Broker) Start(ctx context.Context) error { + b.mu.Lock() + if b.terminal != nil { + err := b.terminal + b.mu.Unlock() + return err + } + if b.started { + b.mu.Unlock() + return errors.New("SDK worker has already started") + } + b.started = true + b.mu.Unlock() + _, err := b.invoke(ctx, func() ([]byte, error) { + b.hooks.initialize() + conn, err := b.hooks.connection() + if err != nil { + return nil, err + } + b.mu.Lock() + b.conn = conn + terminal := b.terminal + b.mu.Unlock() + if terminal != nil { + _ = conn.CloseDeadline(time.Now()) + return nil, terminal + } + go func() { + if notification := <-conn.NotifyClose(make(chan *amqp.Error, 1)); notification != nil { + b.fail(errors.New("MythicContainer SDK connection failed")) + return + } + b.fail(errors.New("MythicContainer SDK connection closed")) + }() + b.hooks.start() + for _, registration := range b.concurrent { + if err := b.startConcurrentRPC(registration); err != nil { + return nil, err + } + } + return nil, nil + }) + return err +} + +func (b *Broker) NotifyClose() <-chan *amqp.Error { return b.closed } + +func (b *Broker) Close() error { + b.fail(errors.New("MythicContainer SDK worker stopped")) + return nil +} + +func (b *Broker) fail(err error) { + b.mu.Lock() + if b.terminal != nil { + b.mu.Unlock() + return + } + b.terminal = err + conn := b.conn + close(b.done) + b.mu.Unlock() + b.closed <- &amqp.Error{Code: amqp.InternalError, Reason: "MythicContainer SDK worker must restart"} + if conn != nil { + _ = conn.CloseDeadline(time.Now()) + } +} + +func (b *Broker) invoke(ctx context.Context, call func() ([]byte, error)) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + b.mu.Lock() + terminal := b.terminal + b.mu.Unlock() + if terminal != nil { + return nil, terminal + } + ctx, cancel := context.WithTimeout(ctx, operationTimeout) + defer cancel() + type result struct { + body []byte + err error + } + done := make(chan result, 1) + go func() { body, err := call(); done <- result{body, err} }() + select { + case <-b.done: + b.mu.Lock() + err := b.terminal + b.mu.Unlock() + return nil, err + case completed := <-done: + if err := ctx.Err(); err != nil { + b.fail(err) + return nil, err + } + if completed.err != nil { + b.fail(completed.err) + } + return completed.body, completed.err + case <-ctx.Done(): + // The SDK does not observe cancellation in every connection/reply wait. + // Never accept further protocol work while a late SDK call may complete. + b.fail(ctx.Err()) + return nil, ctx.Err() + } +} + +func (b *Broker) Call(ctx context.Context, route string, body []byte) ([]byte, error) { + if route == "" || len(body) == 0 || len(body) > MaxBodyBytes { + return nil, errors.New("invalid SDK RPC request") + } + return b.invoke(ctx, func() ([]byte, error) { + // The SDK may retry uncertain publish failures with these exact bytes; + // CUSTOM_TIMEOUT disables automatic retries after a response timeout. + return b.hooks.call(ctx, Exchange, route, body, true, sdk.RPC_RETRY_POLICY_CUSTOM_TIMEOUT) + }) +} + +func (b *Broker) Publish(ctx context.Context, route string, body []byte) error { + if route == "" || len(body) > MaxBodyBytes { + return errors.New("invalid SDK publication") + } + _, err := b.invoke(ctx, func() ([]byte, error) { return nil, b.hooks.publish(ctx, Exchange, route, "", body, false) }) + return err +} + +func (b *Broker) registerCheck(route string, handler Handler) error { + if route == "" || handler == nil { + return errors.New("invalid SDK queue registration") + } + if b.terminal != nil { + return b.terminal + } + if b.started { + return errors.New("register SDK queues before starting worker") + } + return nil +} + +// ConsumeRPC registers a custom SDK RPC queue. Start must complete before +// syncing or activating the durable owner. json.RawMessage preserves the +// JSON response; returning []byte here would base64-encode it again. +func (b *Broker) ConsumeRPC(ctx context.Context, route string, handler Handler) (<-chan error, error) { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.registerCheck(route, handler); err != nil { + return nil, err + } + stopped := make(chan error, 1) + b.hooks.addRPC(sdk.RPCQueueStruct{Exchange: Exchange, Queue: route, RoutingKeyFunction: func(string) string { return route }, ContainerNameFunction: func() string { return "" }, Handler: func(requestCtx context.Context, input []byte) interface{} { + b.mu.Lock() + terminal := b.terminal + b.mu.Unlock() + if terminal != nil { + return json.RawMessage(`{"success":false,"error":"crypto worker is unavailable"}`) + } + requestCtx, cancel := context.WithCancel(requestCtx) + stop := context.AfterFunc(ctx, cancel) + defer stop() + defer cancel() + body, err := handler(requestCtx, input) + if err != nil || !json.Valid(body) || len(body) > MaxBodyBytes { + b.fail(errors.New("SDK crypto handler failed")) + return json.RawMessage(`{"success":false,"error":"crypto worker is unavailable"}`) + } + return json.RawMessage(body) + }}) + return stopped, nil +} + +func (b *Broker) ConsumeDirect(ctx context.Context, route string, handler Handler) (<-chan error, error) { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.registerCheck(route, handler); err != nil { + return nil, err + } + stopped := make(chan error, 1) + b.hooks.addDirect(sdk.DirectQueueStruct{Exchange: Exchange, Queue: route, RoutingKeyFunction: func(string) string { return route }, ContainerNameFunction: func() string { return "" }, Handler: func(requestCtx context.Context, input []byte) { + b.mu.Lock() + terminal := b.terminal + b.mu.Unlock() + if terminal != nil { + return + } + requestCtx, cancel := context.WithCancel(requestCtx) + stop := context.AfterFunc(ctx, cancel) + defer stop() + defer cancel() + if _, err := handler(requestCtx, input); err != nil { + b.fail(errors.New("SDK lifecycle handler failed")) + } + }}) + return stopped, nil +} diff --git a/Payload_Type/crypto_provider/internal/transport/concurrent.go b/Payload_Type/crypto_provider/internal/transport/concurrent.go new file mode 100644 index 0000000..3b3fc3d --- /dev/null +++ b/Payload_Type/crypto_provider/internal/transport/concurrent.go @@ -0,0 +1,165 @@ +package transport + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync" + + sdk "github.com/MythicMeta/MythicContainer/rabbitmq" + amqp "github.com/rabbitmq/amqp091-go" +) + +const concurrentRPCWorkers = 32 + +type concurrentRPC struct { + ctx context.Context + route string + handler Handler +} + +// ConsumeConcurrentRPC bounds parallel business requests on one exclusive queue. +// The SDK's ordinary RPC listener invokes handlers sequentially, so a blocked +// campaign would otherwise prevent independent campaign owners from progressing. +// Connection lifecycle and outgoing storage RPC remain owned by the SDK. +func (b *Broker) ConsumeConcurrentRPC(ctx context.Context, route string, handler Handler) (<-chan error, error) { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.registerCheck(route, handler); err != nil { + return nil, err + } + b.concurrent = append(b.concurrent, concurrentRPC{ctx: ctx, route: route, handler: handler}) + return make(chan error, 1), nil +} + +func (b *Broker) startConcurrentRPC(registration concurrentRPC) error { + if b.hooks.channel == nil { + return errors.New("SDK channel factory is unavailable") + } + ch, err := b.hooks.channel() + if err != nil { + return err + } + ready := false + defer func() { + if !ready { + _ = ch.Close() + } + }() + if err = ch.ExchangeDeclare(Exchange, "direct", true, true, false, false, nil); err != nil { + return err + } + if _, err = ch.QueueDeclare(registration.route, true, true, true, false, nil); err != nil { + return err + } + if err = ch.QueueBind(registration.route, registration.route, Exchange, false, nil); err != nil { + return err + } + if err = ch.Qos(concurrentRPCWorkers, 0, false); err != nil { + return err + } + if err = ch.Confirm(false); err != nil { + return err + } + returned := ch.NotifyReturn(make(chan amqp.Return, 1)) + closed := ch.NotifyClose(make(chan *amqp.Error, 1)) + deliveries, err := ch.Consume(registration.route, "", false, true, false, false, nil) + if err != nil { + return err + } + select { + case <-b.done: + return errors.New("SDK worker stopped before concurrent consumer startup") + default: + } + ready = true + go func() { + select { + case channelErr := <-closed: + if channelErr != nil { + b.fail(channelErr) + } else { + b.fail(errors.New("SDK concurrent RPC channel closed")) + } + case <-b.done: + } + }() + // Handler work proceeds independently; only publication confirmation is + // serialized so mandatory returns can be associated with one exact reply. + publisher := &sync.Mutex{} + for range concurrentRPCWorkers { + go func() { + for { + select { + case <-b.done: + return + case <-registration.ctx.Done(): + return + case delivery, ok := <-deliveries: + if !ok { + b.fail(errors.New("SDK concurrent RPC consumer stopped")) + return + } + if err := b.handleConcurrentRPC(registration, ch, publisher, returned, delivery); err != nil { + b.fail(err) + return + } + } + } + }() + } + return nil +} + +func (b *Broker) handleConcurrentRPC(registration concurrentRPC, ch *amqp.Channel, publisher *sync.Mutex, returned <-chan amqp.Return, delivery amqp.Delivery) error { + requestCtx := registration.ctx + if token, ok := sdk.AuthTokenFromHeaders(delivery.Headers); ok { + requestCtx = sdk.NewContextWithAuthToken(requestCtx, token) + } + ctx, cancel := context.WithTimeout(requestCtx, operationTimeout) + stop := context.AfterFunc(ctx, func() { b.fail(errors.New("SDK concurrent RPC operation timed out")) }) + defer cancel() + defer stop() + select { + case <-b.done: + return errors.New("SDK worker stopped") + default: + } + body, err := registration.handler(ctx, delivery.Body) + if err != nil || !json.Valid(body) || len(body) > MaxBodyBytes || delivery.ReplyTo == "" { + return errors.New("invalid SDK concurrent RPC response") + } + publisher.Lock() + defer publisher.Unlock() + select { + case <-b.done: + return errors.New("SDK worker stopped before reply publication") + default: + } + // RabbitMQ 3.x can return NO_ROUTE for mandatory Direct Reply-To replies + // while still delivering them. Confirm broker acceptance without requiring + // a queue route for that pseudo-address; Mythic retries lost responses. + mandatory := !strings.HasPrefix(delivery.ReplyTo, "amq.rabbitmq.reply-to.") + confirmation, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", delivery.ReplyTo, mandatory, false, amqp.Publishing{ + ContentType: "application/json", Body: body, CorrelationId: delivery.CorrelationId, + }) + if err != nil { + return err + } + confirmed, err := confirmation.WaitContext(ctx) + if err != nil { + return err + } + if !confirmed { + return errors.New("SDK concurrent RPC reply was not confirmed") + } + // RabbitMQ sends a mandatory return before its publication confirmation; + // amqp091-go dispatches returns before completing deferred confirmations. + select { + case <-returned: + return errors.New("SDK concurrent RPC reply was unroutable") + default: + } + return delivery.Ack(false) +} diff --git a/Payload_Type/crypto_provider/internal/wirecheck/storage.go b/Payload_Type/crypto_provider/internal/wirecheck/storage.go new file mode 100644 index 0000000..3c96137 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/wirecheck/storage.go @@ -0,0 +1,167 @@ +package wirecheck + +import ( + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "strings" + + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" +) + +// Storage outcomes that prove nothing was applied, one per storage failure +// code. +var ( + ErrInvalidInput = errors.New("invalid crypto provider state request") + ErrNotFound = errors.New("crypto provider state or result not found") + ErrPreconditionFailed = errors.New("crypto provider state does not match the commit's expectation") + ErrRequestConflict = errors.New("crypto provider request ID has a different input digest") +) + +// PreconditionError names the row whose expectation failed. errors.Is matches +// it to ErrPreconditionFailed. +type PreconditionError struct { + StateID string +} + +func (e *PreconditionError) Error() string { + return fmt.Sprintf("crypto provider state %q does not match the commit's expectation", e.StateID) +} + +func (e *PreconditionError) Is(target error) bool { return target == ErrPreconditionFailed } + +// Limits of Mythic's storage route. +const ( + MaxNamespaceBytes = 128 + MaxStateIDBytes = 256 + MaxRequestIDBytes = 128 + MaxStateBlobBytes = 16 << 20 + MaxProviderJSONBytes = 1 << 20 + // MaxResultBytes bounds one saved result. + MaxResultBytes = 64 << 20 + // MaxCommitRows bounds the distinct state IDs one commit names across its + // expectations, writes and result. + MaxCommitRows = 64 + // MaxCommitWriteBytes bounds the state_blob and provider_json bytes of all + // writes in one commit. + MaxCommitWriteBytes = 32 << 20 +) + +// StateKey checks a row key. +func StateKey(k wire.StateKey) error { + if !validIdentifier(k.Namespace, MaxNamespaceBytes) || !validIdentifier(k.StateID, MaxStateIDBytes) { + return ErrInvalidInput + } + return nil +} + +// LookupResult checks a get_result request. +func LookupResult(r wire.LookupResultRequest) error { + if err := StateKey(r.StateKey); err != nil { + return err + } + if !validIdentifier(r.RequestID, MaxRequestIDBytes) || !validDigest(r.InputDigest) { + return ErrInvalidInput + } + return nil +} + +// Commit checks every rule and limit of a commit that does not depend on +// stored rows. +func Commit(r wire.CommitRequest) error { + if !validIdentifier(r.Namespace, MaxNamespaceBytes) || len(r.Writes) == 0 && r.Result == nil { + return ErrInvalidInput + } + rows := make(map[string]struct{}) + name := func(stateID string) error { + if !validIdentifier(stateID, MaxStateIDBytes) { + return ErrInvalidInput + } + rows[stateID] = struct{}{} + if len(rows) > MaxCommitRows { + return ErrInvalidInput + } + return nil + } + expected := make(map[string]struct{}, len(r.Expect)) + for _, e := range r.Expect { + if err := name(e.StateID); err != nil { + return err + } + if _, duplicate := expected[e.StateID]; duplicate || e.Absent == (e.Revision != 0) || e.Revision < 0 { + return ErrInvalidInput + } + expected[e.StateID] = struct{}{} + } + written := make(map[string]struct{}, len(r.Writes)) + total := 0 + for _, w := range r.Writes { + if err := name(w.StateID); err != nil { + return err + } + if _, duplicate := written[w.StateID]; duplicate { + return ErrInvalidInput + } + written[w.StateID] = struct{}{} + if _, err := NormalizeProviderJSON(w.StateBlob, w.ProviderJSON); err != nil { + return err + } + total += len(w.StateBlob) + len(w.ProviderJSON) + if total > MaxCommitWriteBytes { + return ErrInvalidInput + } + } + if r.Result != nil { + if err := name(r.Result.StateID); err != nil { + return err + } + lookup := wire.LookupResultRequest{StateKey: wire.StateKey{Namespace: r.Namespace, StateID: r.Result.StateID}, RequestID: r.Result.RequestID, InputDigest: r.Result.InputDigest} + if err := LookupResult(lookup); err != nil { + return err + } + if len(r.Result.Result) == 0 || len(r.Result.Result) > MaxResultBytes || !json.Valid(r.Result.Result) { + return ErrInvalidInput + } + } + return nil +} + +// NormalizeProviderJSON checks one row's limits and returns its provider JSON, +// with {} for an omitted value, as Mythic stores it. +func NormalizeProviderJSON(blob []byte, providerJSON json.RawMessage) (json.RawMessage, error) { + if len(blob) > MaxStateBlobBytes || len(providerJSON) > MaxProviderJSONBytes { + return nil, ErrInvalidInput + } + if len(providerJSON) == 0 { + return json.RawMessage(`{}`), nil + } + if !json.Valid(providerJSON) || strings.TrimSpace(string(providerJSON))[0] != '{' { + return nil, ErrInvalidInput + } + return providerJSON, nil +} + +func validIdentifier(value string, limit int) bool { + if value == "" || len(value) > limit { + return false + } + for _, c := range value { + if !identifierRune(c) { + return false + } + } + return true +} + +func identifierRune(c rune) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("._:/-", c) +} + +func validDigest(digest string) bool { + if len(digest) != 64 || digest != strings.ToLower(digest) { + return false + } + _, err := hex.DecodeString(digest) + return err == nil +} diff --git a/Payload_Type/crypto_provider/internal/wirecheck/wirecheck.go b/Payload_Type/crypto_provider/internal/wirecheck/wirecheck.go new file mode 100644 index 0000000..dcef958 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/wirecheck/wirecheck.go @@ -0,0 +1,180 @@ +// Package wirecheck holds the provider's own checks and limits for the +// messages of Mythic's crypto provider API. The SDK declares only the message +// types. These rules follow Mythic's crypto/provider README; Mythic still +// validates every message itself. +package wirecheck + +import ( + "encoding/json" + "errors" + "math" + "regexp" + + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" + "github.com/google/uuid" +) + +const ( + // MaxMessageBytes bounds a request's message and provider JSON, and a + // response's message, agent config and provider JSON. + MaxMessageBytes = 64 << 20 + // MinResultRetentionSeconds is the shortest retention Mythic accepts. While + // a callback exchange is live Mythic may repeat its provider requests, so + // their saved results must outlive the exchange's 300-second lease. + MinResultRetentionSeconds = 300 + // MaxResultRetentionSeconds is the longest retention Mythic accepts: its + // retention job reads the advertised value as a 32-bit integer. + MaxResultRetentionSeconds = math.MaxInt32 + // maxReferenceBytes bounds each profile, session, namespace and state + // reference in a request or response. + maxReferenceBytes = 1024 + maxSchemes = 128 +) + +var identifier = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$`) + +// Name checks a provider's registered name, which is also part of its routing +// key. +func Name(name string) error { + if !identifier.MatchString(name) { + return errors.New("invalid crypto provider name") + } + return nil +} + +// Capabilities checks the capabilities a provider advertises. +func Capabilities(c wire.Capabilities) error { + if c.APIVersion != wire.APIVersion || c.Establishment != "single_round" { + return errors.New("unsupported crypto provider API or establishment mode") + } + if c.SessionPersistence != "durable" && c.SessionPersistence != "volatile" { + return errors.New("invalid crypto provider persistence mode") + } + if len(c.Schemes) == 0 || len(c.Schemes) > maxSchemes || c.MaxMessageBytes < 1 || c.MaxMessageBytes > MaxMessageBytes || + c.ResultRetentionSeconds < MinResultRetentionSeconds || c.ResultRetentionSeconds > MaxResultRetentionSeconds { + return errors.New("invalid crypto provider capabilities") + } + seen := map[string]bool{} + for _, scheme := range c.Schemes { + if !identifier.MatchString(scheme) || seen[scheme] { + return errors.New("invalid or duplicate crypto scheme") + } + seen[scheme] = true + } + return nil +} + +// Request checks one request from Mythic. +func Request(r wire.Request) error { + if r.APIVersion != wire.APIVersion { + return errors.New("unsupported crypto provider API version") + } + if !canonicalUUID(r.RequestID) { + return errors.New("invalid crypto request ID") + } + if r.OperationScopeID <= 0 { + return errors.New("crypto operation scope is required") + } + if len(r.Message) > MaxMessageBytes || len(r.ProviderJSON) > MaxMessageBytes { + return errors.New("crypto provider request exceeds limit") + } + if len(r.ProviderJSON) > 0 && !json.Valid(r.ProviderJSON) { + return errors.New("invalid provider JSON") + } + if r.Scheme != "" && !identifier.MatchString(r.Scheme) { + return errors.New("invalid crypto scheme") + } + for _, value := range []string{r.PayloadUUID, r.NextUUID} { + if value != "" && !canonicalUUID(value) { + return errors.New("invalid crypto request UUID") + } + } + switch r.Method { + case wire.PrepareProfile: + if r.Scheme == "" { + return errors.New("crypto scheme is required") + } + case wire.BeginSession: + if r.ProfileRef == "" || len(r.Message) == 0 { + return errors.New("profile and initial message are required") + } + if r.PayloadUUID == "" || r.NextUUID == "" { + return errors.New("crypto routing claims are required") + } + case wire.Open, wire.Seal: + if r.SessionRef == "" || r.Namespace == "" { + return errors.New("crypto session and namespace are required") + } + default: + return errors.New("unknown crypto provider method") + } + if !referencesFit(r.ProfileRef, r.SessionRef, r.Namespace, r.StateID) { + return errors.New("crypto reference exceeds limit") + } + return nil +} + +// Response checks that r can answer request as Mythic requires. For a failed +// response that is well formed it returns r.Error. +func Response(r wire.Response, request wire.Request) error { + if r.APIVersion != wire.APIVersion || r.RequestID != request.RequestID || r.OperationScopeID != request.OperationScopeID || r.AuthContext != request.AuthContext { + return errors.New("mismatched crypto provider response") + } + if !r.Success { + if r.Error == nil || r.Error.Code == "" { + return errors.New("invalid crypto provider failure") + } + if r.Error.Outcome != "" && r.Error.Outcome != wire.OutcomeRejected && r.Error.Outcome != wire.OutcomeUnresolved { + return errors.New("invalid crypto provider failure outcome") + } + return r.Error + } + if r.Error != nil { + return errors.New("contradictory crypto provider response") + } + if len(r.Message) > MaxMessageBytes || len(r.AgentConfig) > MaxMessageBytes || len(r.ProviderJSON) > MaxMessageBytes { + return errors.New("crypto provider response exceeds limit") + } + if len(r.ProviderJSON) > 0 && !json.Valid(r.ProviderJSON) { + return errors.New("invalid provider response JSON") + } + if !referencesFit(r.ProfileRef, r.SessionRef, r.Namespace, r.StateID) { + return errors.New("crypto response reference exceeds limit") + } + switch request.Method { + case wire.PrepareProfile: + if r.ProfileRef == "" { + return errors.New("provider omitted profile reference") + } + case wire.BeginSession: + if r.SessionRef == "" || r.Namespace == "" || len(r.Message) == 0 { + return errors.New("provider omitted established session or reply") + } + case wire.Open, wire.Seal: + for _, identity := range [][2]string{ + {r.ProfileRef, request.ProfileRef}, + {r.SessionRef, request.SessionRef}, + {r.Namespace, request.Namespace}, + {r.StateID, request.StateID}, + } { + if identity[0] != "" && identity[0] != identity[1] { + return errors.New("mismatched crypto provider session") + } + } + } + return nil +} + +func canonicalUUID(value string) bool { + id, err := uuid.Parse(value) + return err == nil && id.String() == value +} + +func referencesFit(values ...string) bool { + for _, value := range values { + if len(value) > maxReferenceBytes { + return false + } + } + return true +} diff --git a/Payload_Type/crypto_provider/internal/wirecheck/wirecheck_test.go b/Payload_Type/crypto_provider/internal/wirecheck/wirecheck_test.go new file mode 100644 index 0000000..bac5849 --- /dev/null +++ b/Payload_Type/crypto_provider/internal/wirecheck/wirecheck_test.go @@ -0,0 +1,231 @@ +package wirecheck + +import ( + "encoding/json" + "errors" + "strings" + "testing" + + wire "github.com/MythicMeta/MythicContainer/cryptoproviderstructs" + "github.com/google/uuid" +) + +func TestName(t *testing.T) { + for _, name := range []string{"example_crypto", "a", "provider-1.test_x", strings.Repeat("a", 128)} { + if err := Name(name); err != nil { + t.Fatalf("name %q refused: %v", name, err) + } + } + for _, name := range []string{"", "-lead", "bad name", "bad:name", strings.Repeat("a", 129)} { + if Name(name) == nil { + t.Fatalf("name %q accepted", name) + } + } +} + +func TestCapabilities(t *testing.T) { + valid := wire.Capabilities{APIVersion: 1, Schemes: []string{"fixture"}, Establishment: "single_round", SessionPersistence: "durable", MaxMessageBytes: 4096, ResultRetentionSeconds: 3600} + if err := Capabilities(valid); err != nil { + t.Fatal(err) + } + for name, mutate := range map[string]func(*wire.Capabilities){ + "version": func(c *wire.Capabilities) { c.APIVersion++ }, + "establishment": func(c *wire.Capabilities) { c.Establishment = "unknown" }, + "persistence": func(c *wire.Capabilities) { c.SessionPersistence = "unknown" }, + "duplicate": func(c *wire.Capabilities) { c.Schemes = []string{"fixture", "fixture"} }, + "invalid name": func(c *wire.Capabilities) { c.Schemes = []string{"bad:name"} }, + "empty schemes": func(c *wire.Capabilities) { c.Schemes = nil }, + "message size": func(c *wire.Capabilities) { c.MaxMessageBytes = 0 }, + "message limit": func(c *wire.Capabilities) { c.MaxMessageBytes = MaxMessageBytes + 1 }, + "short retention": func(c *wire.Capabilities) { c.ResultRetentionSeconds = MinResultRetentionSeconds - 1 }, + "long retention": func(c *wire.Capabilities) { c.ResultRetentionSeconds = MaxResultRetentionSeconds + 1 }, + } { + t.Run(name, func(t *testing.T) { + candidate := valid + mutate(&candidate) + if Capabilities(candidate) == nil { + t.Fatal("invalid capabilities accepted") + } + }) + } +} + +func TestRequestAndResponse(t *testing.T) { + request := fixtureRequest(wire.Seal) + request.SessionRef, request.Namespace, request.StateID = "session", "fixture", "state" + request.Message = []byte{0, 255, 128} + if err := Request(request); err != nil { + t.Fatal(err) + } + for name, mutate := range map[string]func(*wire.Request){ + "wrong version": func(r *wire.Request) { r.APIVersion++ }, + "invalid request": func(r *wire.Request) { r.RequestID = "bad" }, + "uppercase request": func(r *wire.Request) { r.RequestID = strings.ToUpper(r.RequestID) }, + "missing scope": func(r *wire.Request) { r.OperationScopeID = 0 }, + "missing session": func(r *wire.Request) { r.SessionRef = "" }, + "missing namespace": func(r *wire.Request) { r.Namespace = "" }, + "unknown method": func(r *wire.Request) { r.Method = "unknown" }, + "invalid JSON": func(r *wire.Request) { r.ProviderJSON = json.RawMessage(`{`) }, + "message limit": func(r *wire.Request) { r.Message = make([]byte, MaxMessageBytes+1) }, + "invalid scheme": func(r *wire.Request) { r.Scheme = "bad:scheme" }, + "invalid UUID": func(r *wire.Request) { r.NextUUID = "bad" }, + "long reference": func(r *wire.Request) { r.StateID = strings.Repeat("s", maxReferenceBytes+1) }, + } { + t.Run(name, func(t *testing.T) { + candidate := request + mutate(&candidate) + if Request(candidate) == nil { + t.Fatal("invalid request accepted") + } + }) + } + prepare := fixtureRequest(wire.PrepareProfile) + if Request(prepare) == nil { + t.Fatal("prepare_profile without a scheme accepted") + } + begin := fixtureRequest(wire.BeginSession) + begin.ProfileRef, begin.Message, begin.PayloadUUID = "profile", []byte{1}, uuid.NewString() + if Request(begin) == nil { + t.Fatal("begin_session without its next UUID accepted") + } + + reply := wire.Response{APIVersion: 1, RequestID: request.RequestID, OperationScopeID: request.OperationScopeID, Success: true, AuthContext: request.AuthContext, Message: request.Message} + if err := Response(reply, request); err != nil { + t.Fatal(err) + } + for name, mutate := range map[string]func(*wire.Response){ + "response version": func(r *wire.Response) { r.APIVersion++ }, + "response request": func(r *wire.Response) { r.RequestID = uuid.NewString() }, + "response scope": func(r *wire.Response) { r.OperationScopeID++ }, + "response auth": func(r *wire.Response) { r.AuthContext = "different" }, + "contradiction": func(r *wire.Response) { r.Error = &wire.Failure{Code: "failure"} }, + "failure shape": func(r *wire.Response) { r.Success = false }, + "unknown outcome": func(r *wire.Response) { + r.Success = false + r.Error = &wire.Failure{Code: "failed", Outcome: "unknown-value"} + }, + "response JSON": func(r *wire.Response) { r.ProviderJSON = json.RawMessage(`{`) }, + "response limit": func(r *wire.Response) { r.AgentConfig = make([]byte, MaxMessageBytes+1) }, + } { + t.Run(name, func(t *testing.T) { + candidate := reply + mutate(&candidate) + if Response(candidate, request) == nil { + t.Fatal("invalid response accepted") + } + }) + } + failed := reply + failed.Success = false + var remote *wire.Failure + for _, outcome := range []string{"", wire.OutcomeRejected, wire.OutcomeUnresolved} { + failed.Error = &wire.Failure{Code: "session_unavailable", Outcome: outcome} + if err := Response(failed, request); !errors.As(err, &remote) || remote.Code != "session_unavailable" || remote.Outcome != outcome { + t.Fatalf("failure with outcome %q lost: %v", outcome, err) + } + } + for _, method := range []string{wire.PrepareProfile, wire.BeginSession} { + candidateRequest := fixtureRequest(method) + candidateReply := wire.Response{APIVersion: 1, RequestID: candidateRequest.RequestID, OperationScopeID: candidateRequest.OperationScopeID, AuthContext: candidateRequest.AuthContext, Success: true} + if Response(candidateReply, candidateRequest) == nil { + t.Fatalf("missing %s result accepted", method) + } + } + for _, method := range []string{wire.Open, wire.Seal} { + request.Method = method + request.ProfileRef = "profile" + for _, mutate := range []func(*wire.Response){ + func(r *wire.Response) { r.ProfileRef = "wrong-profile" }, + func(r *wire.Response) { r.SessionRef = "wrong-session" }, + func(r *wire.Response) { r.Namespace = "wrong-namespace" }, + func(r *wire.Response) { r.StateID = "wrong-state" }, + } { + candidate := reply + mutate(&candidate) + if Response(candidate, request) == nil { + t.Fatalf("%s accepted a different session identity", method) + } + } + } +} + +func TestStorageRequests(t *testing.T) { + digest := strings.Repeat("ab", 32) + if err := StateKey(wire.StateKey{Namespace: "ns", StateID: "bc/row:1"}); err != nil { + t.Fatal(err) + } + for _, key := range []wire.StateKey{{Namespace: "", StateID: "a"}, {Namespace: "ns", StateID: "bad id"}, {Namespace: "ns", StateID: strings.Repeat("a", MaxStateIDBytes+1)}} { + if !errors.Is(StateKey(key), ErrInvalidInput) { + t.Fatalf("key %+v accepted", key) + } + } + lookup := wire.LookupResultRequest{StateKey: wire.StateKey{Namespace: "ns", StateID: "a"}, RequestID: "r", InputDigest: digest} + if err := LookupResult(lookup); err != nil { + t.Fatal(err) + } + for _, mutate := range []func(*wire.LookupResultRequest){ + func(r *wire.LookupResultRequest) { r.RequestID = "" }, + func(r *wire.LookupResultRequest) { r.InputDigest = strings.ToUpper(digest) }, + func(r *wire.LookupResultRequest) { r.InputDigest = digest[:62] }, + } { + candidate := lookup + mutate(&candidate) + if !errors.Is(LookupResult(candidate), ErrInvalidInput) { + t.Fatalf("lookup %+v accepted", candidate) + } + } + + commit := wire.CommitRequest{Namespace: "ns", Expect: []wire.Expectation{{StateID: "a", Revision: 1}, {StateID: "b", Absent: true}}, + Writes: []wire.StateWrite{{StateID: "a", StateBlob: []byte{1}}, {StateID: "b", StateBlob: []byte{2}, ProviderJSON: json.RawMessage(`{"k":1}`)}}, + Result: &wire.ResultRecord{StateID: "a", RequestID: "r", InputDigest: digest, Result: json.RawMessage(`{}`)}} + if err := Commit(commit); err != nil { + t.Fatal(err) + } + for name, mutate := range map[string]func(*wire.CommitRequest){ + "empty": func(r *wire.CommitRequest) { r.Writes, r.Result = nil, nil }, + "namespace": func(r *wire.CommitRequest) { r.Namespace = "" }, + "both expectations": func(r *wire.CommitRequest) { r.Expect = []wire.Expectation{{StateID: "a", Revision: 1, Absent: true}} }, + "neither expectation": func(r *wire.CommitRequest) { r.Expect = []wire.Expectation{{StateID: "a"}} }, + "duplicate expect": func(r *wire.CommitRequest) { r.Expect = append(r.Expect, wire.Expectation{StateID: "a", Revision: 2}) }, + "duplicate write": func(r *wire.CommitRequest) { r.Writes = append(r.Writes, wire.StateWrite{StateID: "a"}) }, + "provider JSON array": func(r *wire.CommitRequest) { r.Writes[0].ProviderJSON = json.RawMessage(`[]`) }, + "state blob limit": func(r *wire.CommitRequest) { r.Writes[0].StateBlob = make([]byte, MaxStateBlobBytes+1) }, + "result without value": func(r *wire.CommitRequest) { r.Result.Result = nil }, + "result digest": func(r *wire.CommitRequest) { r.Result.InputDigest = "x" }, + "too many rows": func(r *wire.CommitRequest) { + r.Expect = nil + r.Writes = nil + for i := range MaxCommitRows + 1 { + r.Writes = append(r.Writes, wire.StateWrite{StateID: "row" + strings.Repeat("x", i)}) + } + }, + "write bytes": func(r *wire.CommitRequest) { + r.Writes = nil + for i := range MaxCommitWriteBytes/MaxStateBlobBytes + 1 { + r.Writes = append(r.Writes, wire.StateWrite{StateID: "row" + strings.Repeat("x", i), StateBlob: make([]byte, MaxStateBlobBytes)}) + } + }, + } { + t.Run(name, func(t *testing.T) { + candidate := commit + candidate.Expect = append([]wire.Expectation(nil), commit.Expect...) + candidate.Writes = append([]wire.StateWrite(nil), commit.Writes...) + result := *commit.Result + candidate.Result = &result + mutate(&candidate) + if !errors.Is(Commit(candidate), ErrInvalidInput) { + t.Fatal("invalid commit accepted") + } + }) + } + if normalized, err := NormalizeProviderJSON(nil, nil); err != nil || string(normalized) != "{}" { + t.Fatalf("omitted provider JSON: %s %v", normalized, err) + } + if !errors.Is(&PreconditionError{StateID: "a"}, ErrPreconditionFailed) { + t.Fatal("precondition error does not match its sentinel") + } +} + +func fixtureRequest(method string) wire.Request { + return wire.Request{APIVersion: wire.APIVersion, RequestID: uuid.NewString(), OperationScopeID: 7, Method: method, AuthContext: "transient-context"} +} diff --git a/Payload_Type/crypto_provider/main.go b/Payload_Type/crypto_provider/main.go new file mode 100644 index 0000000..4060554 --- /dev/null +++ b/Payload_Type/crypto_provider/main.go @@ -0,0 +1,33 @@ +package main + +import ( + "context" + "errors" + "flag" + "log" + "os" + "os/signal" + "syscall" + + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/provider" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/service" + "github.com/MythicMeta/ExampleContainers/Payload_Type/crypto_provider/internal/storage" +) + +func main() { + flag.Parse() + if flag.NArg() != 0 { + log.Fatal("unexpected positional argument") + } + config, err := provider.LoadConfig() + if err != nil { + log.Fatal(err) + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := service.Run(ctx, config.Service, func(store storage.Store) (service.Backend, error) { + return provider.New(config, store) + }); err != nil && !errors.Is(err, context.Canceled) { + log.Fatal(err) + } +} diff --git a/README.md b/README.md index 5160943..4d310d0 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,10 @@ This repo serves as an example for the Python and Golang containers that Mythic supports. +## crypto_provider + +[`Payload_Type/crypto_provider`](Payload_Type/crypto_provider) is a standalone Go skeleton for Mythic's crypto-provider API v1. It demonstrates registration, authenticated RPC, the optional opaque state store and the boundary between shared service plumbing and replaceable cryptographic code. Its protocol methods are explicit stubs; see its README to copy only this example into a service repository. + ## go_services `go_services` is an example container that supports: