diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 2d74f891b01fa..80ccf8a13df38 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -2359,6 +2359,7 @@ 'OC\\Security\\Signature\\Model\\OutgoingSignedRequest' => $baseDir . '/lib/private/Security/Signature/Model/OutgoingSignedRequest.php', 'OC\\Security\\Signature\\Model\\Rfc9421IncomingSignedRequest' => $baseDir . '/lib/private/Security/Signature/Model/Rfc9421IncomingSignedRequest.php', 'OC\\Security\\Signature\\Model\\Rfc9421OutgoingSignedRequest' => $baseDir . '/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedRequest.php', + 'OC\\Security\\Signature\\Model\\Rfc9421OutgoingSignedResponse' => $baseDir . '/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedResponse.php', 'OC\\Security\\Signature\\Model\\SignedRequest' => $baseDir . '/lib/private/Security/Signature/Model/SignedRequest.php', 'OC\\Security\\Signature\\Rfc9421\\Algorithm' => $baseDir . '/lib/private/Security/Signature/Rfc9421/Algorithm.php', 'OC\\Security\\Signature\\Rfc9421\\ContentDigest' => $baseDir . '/lib/private/Security/Signature/Rfc9421/ContentDigest.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index 092b81d4a2314..9fb458ae9d9df 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -2400,6 +2400,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OC\\Security\\Signature\\Model\\OutgoingSignedRequest' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Model/OutgoingSignedRequest.php', 'OC\\Security\\Signature\\Model\\Rfc9421IncomingSignedRequest' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Model/Rfc9421IncomingSignedRequest.php', 'OC\\Security\\Signature\\Model\\Rfc9421OutgoingSignedRequest' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedRequest.php', + 'OC\\Security\\Signature\\Model\\Rfc9421OutgoingSignedResponse' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedResponse.php', 'OC\\Security\\Signature\\Model\\SignedRequest' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Model/SignedRequest.php', 'OC\\Security\\Signature\\Rfc9421\\Algorithm' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Rfc9421/Algorithm.php', 'OC\\Security\\Signature\\Rfc9421\\ContentDigest' => __DIR__ . '/../../..' . '/lib/private/Security/Signature/Rfc9421/ContentDigest.php', diff --git a/lib/private/OCM/OCMDiscoveryService.php b/lib/private/OCM/OCMDiscoveryService.php index 996ceaa22b553..d230172da7af2 100644 --- a/lib/private/OCM/OCMDiscoveryService.php +++ b/lib/private/OCM/OCMDiscoveryService.php @@ -15,8 +15,10 @@ use JsonException; use OC\Core\AppInfo\ConfigLexicon; use OC\OCM\Model\OCMProvider; +use OC\Security\Signature\Model\Rfc9421OutgoingSignedResponse; use OCP\AppFramework\Attribute\Consumable; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Response; use OCP\EventDispatcher\IEventDispatcher; use OCP\Federation\ICloudIdManager; use OCP\Http\Client\IClient; @@ -319,6 +321,29 @@ public function confirmRequestOrigin(?string $signedOrigin, string $ocmAddress): } } + /** + * @inheritDoc + * + * @template S of Http::STATUS_* + * @param S $status + * @return Response> + */ + #[\Override] + public function createSignedResponse( + IIncomingSignedRequest $request, + string $body, + int $status = Http::STATUS_OK, + string $contentType = 'application/json; charset=utf-8', + ): Response { + return new Rfc9421OutgoingSignedResponse( + $body, + $request, + new Rfc9421SignatoryManager($this->signatoryManager), + $status, + $contentType, + ); + } + /** * Extract the signer origin (host) from an OCM address (`user@host`). * diff --git a/lib/private/Security/Signature/Model/Rfc9421IncomingSignedRequest.php b/lib/private/Security/Signature/Model/Rfc9421IncomingSignedRequest.php index bc41bf4b1979d..a0072629ac008 100644 --- a/lib/private/Security/Signature/Model/Rfc9421IncomingSignedRequest.php +++ b/lib/private/Security/Signature/Model/Rfc9421IncomingSignedRequest.php @@ -142,7 +142,7 @@ public function __construct( $paramsLine = SignatureBase::serializeSignatureParams($this->components, $this->signatureParams); $this->signatureBaseString = SignatureBase::build( $request->getMethod(), - $this->reconstructTargetUri(), + SignatureBase::reconstructTargetUri($request), $this->collectHeaders(), $this->components, $paramsLine, @@ -304,13 +304,6 @@ private function verifyContentLengthIfCovered(string $body): void { } } - private function reconstructTargetUri(): string { - $scheme = $this->request->getServerProtocol(); - $host = $this->request->getServerHost(); - $path = $this->request->getRequestUri(); - return $scheme . '://' . $host . $path; - } - /** * Collect the HTTP request fields covered by the signature, keyed by their * lowercased name. Derived components (`@*`) are produced inside diff --git a/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedRequest.php b/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedRequest.php index 812d24213dff7..b86ea1b8391d0 100644 --- a/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedRequest.php +++ b/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedRequest.php @@ -61,11 +61,10 @@ public function __construct( ->setSignatory($signatoryManager->getLocalSignatory()) ->setDigestAlgorithm($options['digestAlgorithm'] ?? DigestAlgorithm::SHA256); - $this->signingAlgorithm = (string)($options['rfc9421.signingAlgorithm'] ?? 'ecdsa-p256-sha256'); + $this->signingAlgorithm = SignatureBase::resolveSigningAlgorithm($options); $contentDigestAlgorithm = (string)($options['rfc9421.contentDigestAlgorithm'] ?? ContentDigest::ALGO_SHA256); /** @var list $components */ $components = $options['rfc9421.coveredComponents'] ?? Rfc9421IncomingSignedRequest::REQUIRED_COMPONENTS; - $includeAlg = (bool)($options['rfc9421.includeAlgParameter'] ?? false); $dateHeaderFormat = (string)($options['dateHeader'] ?? SignatureManager::DATE_HEADER); $this->addHeader('Content-Digest', ContentDigest::compute($body, $contentDigestAlgorithm)) @@ -76,17 +75,14 @@ public function __construct( } $this->setHeaderList($components); - $this->signatureParams = [ - 'created' => time(), - 'keyid' => $this->getSignatory()->getKeyId(), - ]; - if ($includeAlg) { - // Off by default per RFC 9421 §3.3.7 (verifier resolves alg from JWK). - $this->signatureParams['alg'] = $this->signingAlgorithm; - } - // integrity-protected marker (RFC 9421 §2.3) identifying this - // signature as the OCM one; the dictionary label is not significant - $this->signatureParams['tag'] = 'ocm'; + // `tag="ocm"` is the integrity-protected marker (RFC 9421 §2.3) + // identifying this signature as the OCM one; the dictionary label is + // not significant. `alg` is off by default per RFC 9421 §3.3.7. + $this->signatureParams = SignatureBase::buildSignatureParams( + $options, + $this->getSignatory()->getKeyId(), + $this->signingAlgorithm, + ); $this->signatureBaseString = SignatureBase::build( $this->method, @@ -166,11 +162,16 @@ public function sign(): self { $this->setSignature(base64_encode($rawSignature)); $paramsLine = SignatureBase::serializeSignatureParams($this->headerList, $this->signatureParams); - $this->addHeader('Signature-Input', 'ocm=' . $paramsLine); - $this->addHeader('Signature', 'ocm=:' . base64_encode($rawSignature) . ':'); + [$signatureInput, $signature] = SignatureBase::formatSignatureHeaders( + SignatureBase::OCM_SIGNATURE_LABEL, + $paramsLine, + $rawSignature, + ); + $this->addHeader('Signature-Input', $signatureInput); + $this->addHeader('Signature', $signature); $this->setSigningElements([ - 'label' => 'ocm', + 'label' => SignatureBase::OCM_SIGNATURE_LABEL, 'components' => implode(' ', $this->headerList), 'params' => $paramsLine, 'signature' => $this->getSignature(), diff --git a/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedResponse.php b/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedResponse.php new file mode 100644 index 0000000000000..4e69514b9ed3e --- /dev/null +++ b/lib/private/Security/Signature/Model/Rfc9421OutgoingSignedResponse.php @@ -0,0 +1,207 @@ +> + */ +final class Rfc9421OutgoingSignedResponse extends Response { + private const COMPONENTS = [ + '@status', + 'content-type', + 'content-digest', + '@method;req', + '@target-uri;req', + 'signature-input;key="ocm";req', + 'signature;key="ocm";req', + ]; + + private bool $signed = false; + private bool $signing = false; + private string $signatureBaseString = ''; + + /** + * @param S $status response status code, covered by the signature + * @param string $contentType value of the signed Content-Type header + * @throws IncomingRequestException if the request is not an RFC 9421 signed request + * @throws SignatoryException if no local private key is available + */ + public function __construct( + private readonly string $body, + private readonly IIncomingSignedRequest $incomingRequest, + private readonly ISignatoryManager $signatoryManager, + int $status = Http::STATUS_OK, + string $contentType = 'application/json; charset=utf-8', + ) { + $options = $signatoryManager->getOptions(); + $digestAlgorithm = (string)($options['rfc9421.contentDigestAlgorithm'] ?? ContentDigest::ALGO_SHA256); + parent::__construct($status, [ + 'Content-Type' => $contentType, + 'Content-Digest' => ContentDigest::compute($body, $digestAlgorithm), + ]); + + $request = $incomingRequest->getRequest(); + if ($request->getHeader('Signature-Input') === '' || $request->getHeader('Signature') === '') { + throw new IncomingRequestException('RFC 9421 signed request required'); + } + if ($signatoryManager->getLocalSignatory()->getPrivateKey() === '') { + throw new SignatoryException('empty private key'); + } + } + + #[\Override] + public function setStatus($status): static { + $this->signed = false; + return parent::setStatus($status); + } + + #[\Override] + public function addHeader($name, $value) { + if (!$this->signing) { + $this->signed = false; + } + return parent::addHeader($name, $value); + } + + #[\Override] + public function setHeaders(array $headers): static { + $this->signed = false; + return parent::setHeaders($headers); + } + + #[\Override] + public function getStatus() { + $this->sign(); + return parent::getStatus(); + } + + #[\Override] + public function getHeaders() { + $this->sign(); + return parent::getHeaders(); + } + + #[\Override] + public function render(): string { + $this->sign(); + return $this->body; + } + + public function getSignatureBaseString(): string { + $this->sign(); + return $this->signatureBaseString; + } + + /** + * Compute and attach the signature headers from the current status and + * headers. Runs at most once between mutations of the response. + */ + private function sign(): void { + if ($this->signed || $this->signing) { + return; + } + $this->signing = true; + try { + $options = $this->signatoryManager->getOptions(); + $signatory = $this->signatoryManager->getLocalSignatory(); + $signingAlgorithm = SignatureBase::resolveSigningAlgorithm($options); + $paramsLine = SignatureBase::serializeSignatureParams( + self::COMPONENTS, + SignatureBase::buildSignatureParams($options, $signatory->getKeyId(), $signingAlgorithm), + ); + + $request = $this->incomingRequest->getRequest(); + $this->signatureBaseString = SignatureBase::buildResponse( + status: parent::getStatus(), + responseHeaders: $this->responseHeadersByLowercaseName(), + requestMethod: $request->getMethod(), + requestUri: SignatureBase::reconstructTargetUri($request), + requestHeaders: $this->collectRequestHeaders($request), + components: self::COMPONENTS, + signatureParamsLine: $paramsLine, + ); + + $rawSignature = Algorithm::sign( + $this->signatureBaseString, + $signatory->getPrivateKey(), + $signingAlgorithm, + ); + [$signatureInput, $signature] = SignatureBase::formatSignatureHeaders( + SignatureBase::OCM_SIGNATURE_LABEL, + $paramsLine, + $rawSignature, + ); + parent::addHeader('Signature-Input', $signatureInput); + parent::addHeader('Signature', $signature); + $this->signed = true; + } finally { + $this->signing = false; + } + } + + /** + * @return array + */ + private function responseHeadersByLowercaseName(): array { + $out = []; + foreach (parent::getHeaders() as $name => $value) { + $out[strtolower($name)] = (string)$value; + } + return $out; + } + + /** + * Plain request fields covered by `;req` components, keyed by lowercase name. + * + * @return array + * @throws SignatureException when a covered request field is missing + */ + private function collectRequestHeaders(IRequest $request): array { + $out = []; + foreach (self::COMPONENTS as $component) { + [$name, $req] = SignatureBase::parseComponentIdentifier($component); + if (!$req || str_starts_with($name, '@')) { + continue; + } + $value = $request->getHeader($name); + if ($value === '') { + throw new SignatureException('missing request field for signature: ' . $name); + } + $out[strtolower($name)] = $value; + } + return $out; + } +} diff --git a/lib/private/Security/Signature/Rfc9421/SignatureBase.php b/lib/private/Security/Signature/Rfc9421/SignatureBase.php index d3684d0251f20..6230552e723bb 100644 --- a/lib/private/Security/Signature/Rfc9421/SignatureBase.php +++ b/lib/private/Security/Signature/Rfc9421/SignatureBase.php @@ -9,20 +9,35 @@ namespace OC\Security\Signature\Rfc9421; +use gapple\StructuredFields\Dictionary; +use gapple\StructuredFields\ParseException; +use gapple\StructuredFields\Parser; +use gapple\StructuredFields\Serializer; +use gapple\StructuredFields\TupleInterface; use InvalidArgumentException; +use OCP\IRequest; use OCP\Security\Signature\Exceptions\SignatureException; /** * RFC 9421 §2.5 signature base construction. Implements the derived * components OCM uses (`@method`, `@target-uri`, `@authority`, `@scheme`, - * `@path`, `@query`, `@request-target`) plus plain HTTP fields. + * `@path`, `@query`, `@request-target`, `@status`) plus plain HTTP fields. + * + * Component identifiers may carry the `;req` parameter (component of the + * triggering request, only valid in response signatures) and the + * `;key="..."` parameter (a single member of a structured field, e.g. one + * entry of the Signature-Input dictionary). */ final class SignatureBase { + public const DEFAULT_SIGNING_ALGORITHM = 'ecdsa-p256-sha256'; + public const OCM_SIGNATURE_LABEL = 'ocm'; + public const OCM_SIGNATURE_TAG = 'ocm'; + /** * @param array $headers headers keyed by lowercase name * @param list $components covered component identifiers, in order * @param string $signatureParamsLine `(...);params...` for `@signature-params` - * @throws SignatureException when a covered field is missing from $headers + * @throws SignatureException when a component identifier is malformed or a covered field is missing from $headers */ public static function build( string $method, @@ -31,9 +46,53 @@ public static function build( array $components, string $signatureParamsLine, ): string { + return self::buildBase($components, $signatureParamsLine, static function (string $name, bool $req, ?string $key) use ($method, $uri, $headers): string { + if ($req) { + throw new SignatureException(';req is only valid in response signatures: ' . $name); + } + return self::requestComponentValue($name, $key, $method, $uri, $headers); + }); + } + + /** + * Build a response signature base with optional components from the + * request that triggered the response. + * + * @param array $responseHeaders response headers keyed by lowercase name + * @param array $requestHeaders request headers keyed by lowercase name + * @param list $components covered component identifiers, in order + * @param string $signatureParamsLine `(...);params...` for `@signature-params` + * @throws SignatureException when a component identifier is malformed or a covered field is missing + */ + public static function buildResponse( + int $status, + array $responseHeaders, + string $requestMethod, + string $requestUri, + array $requestHeaders, + array $components, + string $signatureParamsLine, + ): string { + return self::buildBase($components, $signatureParamsLine, static function (string $name, bool $req, ?string $key) use ($status, $responseHeaders, $requestMethod, $requestUri, $requestHeaders): string { + if ($req) { + return self::requestComponentValue($name, $key, $requestMethod, $requestUri, $requestHeaders); + } + if ($key !== null) { + throw new SignatureException(';key is only valid together with ;req: ' . $name); + } + return self::responseComponentValue($name, $status, $responseHeaders); + }); + } + + /** + * @param list $components + * @param callable(string, bool, ?string): string $valueResolver receives (name, req, key) + */ + private static function buildBase(array $components, string $signatureParamsLine, callable $valueResolver): string { $lines = []; foreach ($components as $component) { - $lines[] = '"' . $component . '": ' . self::componentValue($component, $method, $uri, $headers); + [$name, $req, $key] = self::parseComponentIdentifier($component); + $lines[] = self::serializeComponentIdentifier($name, $req, $key) . ': ' . $valueResolver($name, $req, $key); } $lines[] = '"@signature-params": ' . $signatureParamsLine; return implode("\n", $lines); @@ -45,9 +104,14 @@ public static function build( * * @param list $components * @param array $params + * @throws SignatureException when a component identifier is malformed */ public static function serializeSignatureParams(array $components, array $params): string { - $inner = array_map(static fn (string $c): string => '"' . $c . '"', $components); + $inner = []; + foreach ($components as $component) { + [$name, $req, $key] = self::parseComponentIdentifier($component); + $inner[] = self::serializeComponentIdentifier($name, $req, $key); + } $out = '(' . implode(' ', $inner) . ')'; foreach ($params as $name => $value) { $out .= ';' . $name . '=' . self::serializeBareItem($value); @@ -55,6 +119,92 @@ public static function serializeSignatureParams(array $components, array $params return $out; } + /** + * Parse a component identifier into name and parameters. + * + * @return array{string, bool, ?string} [name, req, key] + * @throws SignatureException on malformed identifiers + */ + public static function parseComponentIdentifier(string $component): array { + $len = strlen($component); + $i = 0; + while ($i < $len && $component[$i] !== ';') { + $i++; + } + $name = substr($component, 0, $i); + if (!preg_match('/^(?:@[a-z][a-z0-9-]*|[a-z*][a-z0-9_*-]*(?:\.[a-z0-9_*-]+)*)$/', $name)) { + throw new SignatureException('invalid component identifier: ' . $component); + } + + $req = false; + $key = null; + while ($i < $len) { + $i++; // consume ';' + $paramStart = $i; + while ($i < $len && $component[$i] !== '=' && $component[$i] !== ';') { + $i++; + } + $paramName = substr($component, $paramStart, $i - $paramStart); + $paramValue = true; + if ($i < $len && $component[$i] === '=') { + $i++; + if ($i < $len && $component[$i] === '"') { + $i++; + $value = ''; + while ($i < $len && $component[$i] !== '"') { + if ($component[$i] === '\\' && $i + 1 < $len) { + $value .= $component[$i + 1]; + $i += 2; + continue; + } + $value .= $component[$i]; + $i++; + } + if ($i >= $len) { + throw new SignatureException('unterminated string in component identifier: ' . $component); + } + $i++; // closing quote + $paramValue = $value; + } else { + $valueStart = $i; + while ($i < $len && $component[$i] !== ';') { + $i++; + } + $paramValue = substr($component, $valueStart, $i - $valueStart); + } + } + switch ($paramName) { + case 'req': + if ($paramValue !== true) { + throw new SignatureException(';req takes no value: ' . $component); + } + $req = true; + break; + case 'key': + if (!is_string($paramValue) || $paramValue === '') { + throw new SignatureException(';key requires a non-empty string value: ' . $component); + } + $key = $paramValue; + break; + default: + throw new SignatureException('unsupported component identifier parameter ";' . $paramName . '": ' . $component); + } + } + return [$name, $req, $key]; + } + + /** Serialize a parsed component identifier, e.g. `"signature-input";key="ocm";req`. */ + public static function serializeComponentIdentifier(string $name, bool $req, ?string $key): string { + $out = '"' . $name . '"'; + if ($key !== null) { + $out .= ';key=' . self::serializeBareItem($key); + } + if ($req) { + $out .= ';req'; + } + return $out; + } + /** * @param scalar $value */ @@ -71,17 +221,113 @@ public static function serializeBareItem(mixed $value): string { throw new InvalidArgumentException('unsupported parameter value type'); } - private static function componentValue(string $component, string $method, string $uri, array $headers): string { - if (str_starts_with($component, '@')) { - return self::derivedValue($component, $method, $uri); + /** Reconstruct the absolute target URI of an incoming request. */ + public static function reconstructTargetUri(IRequest $request): string { + return $request->getServerProtocol() . '://' . $request->getServerHost() . $request->getRequestUri(); + } + + /** + * RFC 9421 alg name (e.g. `ecdsa-p256-sha256`) from the signatory manager options. + * + * @param array $options + */ + public static function resolveSigningAlgorithm(array $options): string { + return (string)($options['rfc9421.signingAlgorithm'] ?? self::DEFAULT_SIGNING_ALGORITHM); + } + + /** + * Signature parameters of an OCM signature: `created`, `keyid` and the + * integrity-protected `tag="ocm"`, plus `alg` when + * `rfc9421.includeAlgParameter` is set (off by default, RFC 9421 §3.3.7). + * + * @param array $options signatory manager options + * @return array + */ + public static function buildSignatureParams(array $options, string $keyId, string $signingAlgorithm): array { + $params = [ + 'created' => time(), + 'keyid' => $keyId, + 'tag' => self::OCM_SIGNATURE_TAG, + ]; + if ((bool)($options['rfc9421.includeAlgParameter'] ?? false)) { + $params['alg'] = $signingAlgorithm; + } + return $params; + } + + /** + * Signature-Input / Signature header values for one signature label. + * + * @return array{0: string, 1: string} + */ + public static function formatSignatureHeaders(string $label, string $signatureParamsLine, string $rawSignature): array { + return [ + $label . '=' . $signatureParamsLine, + $label . '=:' . base64_encode($rawSignature) . ':', + ]; + } + + private static function requestComponentValue(string $name, ?string $key, string $method, string $uri, array $headers): string { + if (str_starts_with($name, '@')) { + if ($key !== null) { + throw new SignatureException(';key is not allowed on derived component: ' . $name); + } + return self::derivedValue($name, $method, $uri); } - $lower = strtolower($component); + $lower = strtolower($name); if (!array_key_exists($lower, $headers)) { - throw new SignatureException('missing field for signature: ' . $component); + throw new SignatureException('missing field for signature: ' . $name); + } + $value = $headers[$lower]; + if ($key !== null) { + return self::dictionaryMemberValue($lower, $key, $value); + } + return self::normalizeFieldValue($value); + } + + private static function responseComponentValue(string $name, int $status, array $headers): string { + if ($name === '@status') { + return (string)$status; + } + if (str_starts_with($name, '@')) { + throw new SignatureException('unsupported response derived component: ' . $name); + } + $lower = strtolower($name); + if (!array_key_exists($lower, $headers)) { + throw new SignatureException('missing field for signature: ' . $name); } return self::normalizeFieldValue($headers[$lower]); } + /** + * Value of a `;key="..."` component: the single dictionary member + * `label=item` of a structured field (RFC 8941). + */ + private static function dictionaryMemberValue(string $field, string $key, string $value): string { + try { + $dict = Parser::parseDictionary($value); + } catch (ParseException $e) { + throw new SignatureException('field ' . $field . ' is not a valid dictionary: ' . $e->getMessage(), 0, $e); + } + $entry = null; + foreach ($dict as $label => $item) { + if ($label === $key) { + $entry = $item; + break; + } + } + if ($entry === null) { + throw new SignatureException('dictionary entry "' . $key . '" missing in field: ' . $field); + } + if ($entry === true) { + return $key; + } + if (!$entry instanceof TupleInterface) { + throw new SignatureException('unsupported dictionary entry for "' . $key . '" in field: ' . $field); + } + return Serializer::serializeDictionary(Dictionary::fromArray([$key => $entry])); + } + private static function derivedValue(string $component, string $method, string $uri): string { $parts = parse_url($uri); if ($parts === false) { diff --git a/lib/public/OCM/IOCMDiscoveryService.php b/lib/public/OCM/IOCMDiscoveryService.php index 92c705be41d2f..39d8fd09bb36d 100644 --- a/lib/public/OCM/IOCMDiscoveryService.php +++ b/lib/public/OCM/IOCMDiscoveryService.php @@ -10,12 +10,15 @@ namespace OCP\OCM; use OCP\AppFramework\Attribute\Consumable; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Response; use OCP\Http\Client\IClient; use OCP\Http\Client\IResponse; use OCP\OCM\Events\LocalOCMDiscoveryEvent; use OCP\OCM\Exceptions\OCMCapabilityException; use OCP\OCM\Exceptions\OCMProviderException; use OCP\Security\Signature\Exceptions\IncomingRequestException; +use OCP\Security\Signature\Exceptions\SignatureException; use OCP\Security\Signature\IIncomingSignedRequest; /** @@ -83,6 +86,32 @@ public function getIncomingSignedRequest(?string $ocmAddress = null): ?IIncoming */ public function confirmRequestOrigin(?string $signedOrigin, string $ocmAddress): void; + /** + * Create an RFC 9421 signed OCM response bound to an incoming request. + * + * The returned response renders the exact bytes supplied in `$body`. + * The signature is computed when the response is sent, so the status + * and headers of the returned response may still be adjusted. + * + * @template S of Http::STATUS_* + * + * @param IIncomingSignedRequest $request verified incoming OCM request + * @param string $body exact response body to sign and return + * @param S $status response status code, covered by the signature + * @param string $contentType value of the signed Content-Type header + * @return Response> + * + * @throws IncomingRequestException if the request is not an RFC 9421 signed request + * @throws SignatureException if the response cannot be signed + * @since 36.0.0 + */ + public function createSignedResponse( + IIncomingSignedRequest $request, + string $body, + int $status = Http::STATUS_OK, + string $contentType = 'application/json; charset=utf-8', + ): Response; + /** * Request a remote OCM endpoint. * diff --git a/tests/lib/OCM/DiscoveryServiceTest.php b/tests/lib/OCM/DiscoveryServiceTest.php index 7d872be30b856..591eeceadfcfa 100644 --- a/tests/lib/OCM/DiscoveryServiceTest.php +++ b/tests/lib/OCM/DiscoveryServiceTest.php @@ -11,12 +11,16 @@ use OC\AppFramework\Bootstrap\RegistrationContext; use OC\OCM\OCMDiscoveryService; +use OC\Security\Signature\Rfc9421\ContentDigest; use OCA\CloudFederationAPI\Controller\OCMRequestController; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IAppConfig; use OCP\IConfig; +use OCP\IRequest; use OCP\IURLGenerator; use OCP\OCM\Events\LocalOCMDiscoveryEvent; use OCP\OCM\Events\OCMEndpointRequestEvent; +use OCP\Security\Signature\IIncomingSignedRequest; use OCP\Server; use Psr\Log\LoggerInterface; use ReflectionClass; @@ -149,6 +153,42 @@ public function testLocalDiscoveryAdvertisesJwksUri(): void { $this->assertStringContainsString('cloud_federation_api/api/v1/jwks', $jwksUri); } + public function testCreateSignedResponse(): void { + Server::get(IAppConfig::class)->deleteKey('core', 'ocm_jwks_slot_active'); + + $request = $this->createMock(IRequest::class); + $requestHeaders = [ + 'signature-input' => 'ocm=("@method");created=1;keyid="remote";nonce="nonce-1";tag="ocm"', + 'signature' => 'ocm=:' . base64_encode(random_bytes(64)) . ':', + ]; + $request->method('getHeader') + ->willReturnCallback(static fn (string $name) => $requestHeaders[strtolower($name)] ?? ''); + $request->method('getMethod')->willReturn('GET'); + $request->method('getServerProtocol')->willReturn('https'); + $request->method('getServerHost')->willReturn('cloud.example.org'); + $request->method('getRequestUri')->willReturn('/ocm/mls-key-packages?userId=alice'); + $incoming = $this->createMock(IIncomingSignedRequest::class); + $incoming->method('getRequest')->willReturn($request); + + $response = $this->discoveryService->createSignedResponse( + $incoming, + '{"keyPackages":[]}', + ); + $headers = $response->getHeaders(); + + $this->assertSame(200, $response->getStatus()); + $this->assertSame('{"keyPackages":[]}', $response->render()); + $this->assertSame( + ContentDigest::compute('{"keyPackages":[]}', ContentDigest::ALGO_SHA256), + $headers['Content-Digest'], + ); + $this->assertSame('application/json; charset=utf-8', $headers['Content-Type']); + $this->assertArrayHasKey('Signature-Input', $headers); + $this->assertArrayHasKey('Signature', $headers); + $this->assertStringContainsString('"signature-input";key="ocm";req', $headers['Signature-Input']); + $this->assertStringContainsString('"signature";key="ocm";req', $headers['Signature-Input']); + } + public function testLocalAddedCapability(): void { $this->context->for('ocm-capability-app')->registerEventListener(LocalOCMDiscoveryEvent::class, LocalOCMDiscoveryTestEvent::class); $this->context->delegateEventListenerRegistrations($this->dispatcher); diff --git a/tests/lib/Security/Signature/Model/Rfc9421RoundTripTest.php b/tests/lib/Security/Signature/Model/Rfc9421RoundTripTest.php index 4639c1145b8d3..5b9ca815cac19 100644 --- a/tests/lib/Security/Signature/Model/Rfc9421RoundTripTest.php +++ b/tests/lib/Security/Signature/Model/Rfc9421RoundTripTest.php @@ -12,14 +12,18 @@ use Firebase\JWT\JWK; use OC\Security\Signature\Model\Rfc9421IncomingSignedRequest; use OC\Security\Signature\Model\Rfc9421OutgoingSignedRequest; +use OC\Security\Signature\Model\Rfc9421OutgoingSignedResponse; use OC\Security\Signature\Rfc9421\Algorithm; use OC\Security\Signature\Rfc9421\ContentDigest; +use OCP\AppFramework\Http; use OCP\IRequest; use OCP\Security\Signature\Enum\DigestAlgorithm; use OCP\Security\Signature\Enum\SignatureAlgorithm; use OCP\Security\Signature\Exceptions\IncomingRequestException; use OCP\Security\Signature\Exceptions\InvalidSignatureException; +use OCP\Security\Signature\Exceptions\SignatureException; use OCP\Security\Signature\Exceptions\SignatureNotFoundException; +use OCP\Security\Signature\IIncomingSignedRequest; use OCP\Security\Signature\ISignatoryManager; use OCP\Security\Signature\Model\Signatory; use Test\TestCase; @@ -50,6 +54,187 @@ public function testEcdsaP256RoundTripVerifies(): void { $this->addToAssertionCount(1); } + public function testSignedResponseVerifiesAndBindsRequest(): void { + [$signatory, $jwk] = $this->ecdsaP256Material('https://sender.example.org/ocm#ecdsa-p256-sha256'); + $signatoryManager = $this->makeSignatoryManager($signatory); + $requestSignatureInput = 'ocm=("@method" "@target-uri");created=1;keyid="remote";nonce="nonce-1";tag="ocm"'; + $requestSignature = 'ocm=:' . base64_encode(random_bytes(64)) . ':'; + $request = $this->mockRequest( + [ + 'Signature-Input' => $requestSignatureInput . ', proxy=("@method");created=1;keyid="proxy"', + 'Signature' => $requestSignature . ', proxy=:' . base64_encode(random_bytes(64)) . ':', + ], + 'GET', + '/ocm/mls-key-packages?userId=alice%40sender.example.org', + 'sender.example.org', + ); + $incoming = $this->createMock(IIncomingSignedRequest::class); + $incoming->method('getRequest')->willReturn($request); + $response = new Rfc9421OutgoingSignedResponse( + '{"keyPackages":[]}', + $incoming, + $signatoryManager, + ); + + $headers = $response->getHeaders(); + $this->assertStringContainsString('"@method";req', $headers['Signature-Input']); + $this->assertStringContainsString('"@target-uri";req', $headers['Signature-Input']); + $this->assertStringContainsString('"signature-input";key="ocm";req', $headers['Signature-Input']); + $this->assertStringContainsString('"signature";key="ocm";req', $headers['Signature-Input']); + + $base = $response->getSignatureBaseString(); + // only the ocm dictionary entries of the request are covered, not + // the proxy-added sibling entries + $this->assertStringContainsString('"signature-input";key="ocm";req: ' . $requestSignatureInput, $base); + $this->assertStringContainsString('"signature";key="ocm";req: ' . $requestSignature, $base); + $this->assertStringNotContainsString('proxy=', $base); + + $this->assertSame( + 1, + preg_match('/^ocm=:([^:]+):$/', $headers['Signature'], $matches), + ); + $rawSignature = base64_decode($matches[1], true); + $this->assertIsString($rawSignature); + $this->assertTrue(Algorithm::verify( + $base, + $rawSignature, + $jwk, + null, + )); + // a different request signature (e.g. a replayed response for + // another request to the same URI) must not verify + $this->assertFalse(Algorithm::verify( + str_replace($requestSignature, 'ocm=:' . base64_encode(random_bytes(64)) . ':', $base), + $rawSignature, + $jwk, + null, + )); + $this->assertFalse(Algorithm::verify( + str_replace('nonce-1', 'nonce-2', $base), + $rawSignature, + $jwk, + null, + )); + } + + public function testSignedResponseResignsAfterMutation(): void { + [$signatory, $jwk] = $this->ecdsaP256Material('https://sender.example.org/ocm#ecdsa-p256-sha256'); + $signatoryManager = $this->makeSignatoryManager($signatory); + $request = $this->mockRequest( + [ + 'Signature-Input' => 'ocm=("@method");created=1;keyid="remote";tag="ocm"', + 'Signature' => 'ocm=:' . base64_encode(random_bytes(64)) . ':', + ], + 'GET', + '/ocm/mls-key-packages', + 'sender.example.org', + ); + $incoming = $this->createMock(IIncomingSignedRequest::class); + $incoming->method('getRequest')->willReturn($request); + $response = new Rfc9421OutgoingSignedResponse( + '{"error":"nope"}', + $incoming, + $signatoryManager, + ); + + $this->assertStringContainsString('"@status": 200', $response->getSignatureBaseString()); + + // a controller or middleware adjusting the response afterwards must + // not leave a stale signature behind + $response->setStatus(Http::STATUS_BAD_REQUEST); + $response->addHeader('Content-Type', 'application/problem+json'); + + $base = $response->getSignatureBaseString(); + $this->assertStringContainsString('"@status": 400', $base); + $this->assertStringContainsString('"content-type": application/problem+json', $base); + $headers = $response->getHeaders(); + $this->assertSame(400, $response->getStatus()); + $this->assertSame('application/problem+json', $headers['Content-Type']); + $this->assertSame( + 1, + preg_match('/^ocm=:([^:]+):$/', $headers['Signature'], $matches), + ); + $this->assertTrue(Algorithm::verify( + $base, + base64_decode($matches[1], true), + $jwk, + null, + )); + } + + public function testSignedResponseWithCustomStatusAndContentType(): void { + [$signatory, $jwk] = $this->ecdsaP256Material('https://sender.example.org/ocm#ecdsa-p256-sha256'); + $signatoryManager = $this->makeSignatoryManager($signatory); + $request = $this->mockRequest( + [ + 'Signature-Input' => 'ocm=("@method");created=1;keyid="remote";tag="ocm"', + 'Signature' => 'ocm=:' . base64_encode(random_bytes(64)) . ':', + ], + 'POST', + '/ocm/shares', + 'sender.example.org', + ); + $incoming = $this->createMock(IIncomingSignedRequest::class); + $incoming->method('getRequest')->willReturn($request); + $response = new Rfc9421OutgoingSignedResponse( + '{"message":"forbidden"}', + $incoming, + $signatoryManager, + Http::STATUS_FORBIDDEN, + 'application/json', + ); + + $this->assertSame(403, $response->getStatus()); + $this->assertSame('{"message":"forbidden"}', $response->render()); + $headers = $response->getHeaders(); + $this->assertSame('application/json', $headers['Content-Type']); + $base = $response->getSignatureBaseString(); + $this->assertStringContainsString('"@status": 403', $base); + $this->assertStringContainsString('"content-type": application/json', $base); + $this->assertSame( + 1, + preg_match('/^ocm=:([^:]+):$/', $headers['Signature'], $matches), + ); + $this->assertTrue(Algorithm::verify( + $base, + base64_decode($matches[1], true), + $jwk, + null, + )); + } + + public function testMalformedComponentIdentifierRejectedAsSignatureException(): void { + // a component name like "a;b" comes straight from the remote + // Signature-Input and must surface as SignatureException (mapped to + // a 400 with throttling), never as an uncaught + // InvalidArgumentException (HTTP 500) + $body = 'msg'; + $headers = [ + 'Content-Digest' => ContentDigest::compute($body, ContentDigest::ALGO_SHA256), + 'Content-Length' => (string)strlen($body), + 'Signature-Input' => 'ocm=("@method" "@target-uri" "content-digest" "content-length" "a;b");created=' . time() . ';keyid="remote";tag="ocm"', + 'Signature' => 'ocm=:' . base64_encode(random_bytes(64)) . ':', + ]; + $req = $this->mockRequest($headers, 'POST', '/ocm/shares', 'receiver.example.org'); + + $this->expectException(SignatureException::class); + new Rfc9421IncomingSignedRequest($body, $req); + } + + public function testSignedResponseRequiresRfc9421Request(): void { + $incoming = $this->createMock(IIncomingSignedRequest::class); + $incoming->method('getRequest')->willReturn( + $this->mockRequest([], 'GET', '/ocm/mls-key-packages', 'sender.example.org'), + ); + + $this->expectException(IncomingRequestException::class); + new Rfc9421OutgoingSignedResponse( + 'body', + $incoming, + $this->createMock(ISignatoryManager::class), + ); + } + public function testEd25519VerifyAcceptedWhenSodiumLoaded(): void { $this->skipUnlessSodium(); [$signatory, $jwk] = $this->ed25519Material('https://sender.example.org/ocm#ecdsa-p256-sha256'); diff --git a/tests/lib/Security/Signature/Rfc9421/SignatureBaseTest.php b/tests/lib/Security/Signature/Rfc9421/SignatureBaseTest.php index d5aed5e9ab679..16c29823b07ea 100644 --- a/tests/lib/Security/Signature/Rfc9421/SignatureBaseTest.php +++ b/tests/lib/Security/Signature/Rfc9421/SignatureBaseTest.php @@ -73,6 +73,93 @@ public function testSerializeSignatureParams(): void { $this->assertSame('("@method" "@target-uri");created=100;keyid="kid";expires=200', $line); } + public function testBuildResponseWithRequestComponents(): void { + $components = [ + '@status', + 'content-type', + 'content-digest', + '@method;req', + '@target-uri;req', + 'signature-input;key="ocm";req', + 'signature;key="ocm";req', + ]; + $params = SignatureBase::serializeSignatureParams( + $components, + ['created' => 100, 'keyid' => 'kid', 'tag' => 'ocm'], + ); + + $base = SignatureBase::buildResponse( + status: 200, + responseHeaders: [ + 'content-type' => 'application/json', + 'content-digest' => 'sha-256=:response:', + ], + requestMethod: 'GET', + requestUri: 'https://example.org/ocm/mls-key-packages?userId=alice', + requestHeaders: [ + 'signature-input' => 'proxy=("@method");created=1, ocm=("@method");created=1;nonce="n";tag="ocm"', + 'signature' => 'proxy=:AAAA:, ocm=:BBBB:', + ], + components: $components, + signatureParamsLine: $params, + ); + + $expected = '"@status": 200' . "\n" + . '"content-type": application/json' . "\n" + . '"content-digest": sha-256=:response:' . "\n" + . '"@method";req: GET' . "\n" + . '"@target-uri";req: https://example.org/ocm/mls-key-packages?userId=alice' . "\n" + . '"signature-input";key="ocm";req: ocm=("@method");created=1;nonce="n";tag="ocm"' . "\n" + . '"signature";key="ocm";req: ocm=:BBBB:' . "\n" + . '"@signature-params": ("@status" "content-type" "content-digest" "@method";req "@target-uri";req "signature-input";key="ocm";req "signature";key="ocm";req);created=100;keyid="kid";tag="ocm"'; + $this->assertSame($expected, $base); + } + + public function testKeyedComponentWithMissingDictionaryEntryThrows(): void { + $this->expectException(SignatureException::class); + SignatureBase::buildResponse( + status: 200, + responseHeaders: ['content-type' => 'application/json'], + requestMethod: 'GET', + requestUri: 'https://example.org/ocm/x', + requestHeaders: ['signature-input' => 'proxy=("@method");created=1'], + components: ['signature-input;key="ocm";req'], + signatureParamsLine: '()', + ); + } + + public function testMalformedComponentIdentifierThrowsSignatureException(): void { + // a component name containing ';' (e.g. "a;b" from a remote + // Signature-Input) must surface as SignatureException, not as an + // uncaught InvalidArgumentException + foreach (['a;b', '', 'content-type;sf', '"quoted"', 'x;key='] as $component) { + try { + SignatureBase::serializeSignatureParams([$component], ['created' => 1]); + $this->fail('expected SignatureException for ' . $component); + } catch (SignatureException) { + $this->addToAssertionCount(1); + } + try { + SignatureBase::build('GET', 'https://example.org/', [], [$component], '()'); + $this->fail('expected SignatureException for ' . $component); + } catch (SignatureException) { + $this->addToAssertionCount(1); + } + } + } + + public function testBuildRejectsReqParameterInRequestSignature(): void { + $this->expectException(SignatureException::class); + SignatureBase::build('GET', 'https://example.org/', [], ['@method;req'], '()'); + } + + public function testParseComponentIdentifier(): void { + $this->assertSame(['@method', false, null], SignatureBase::parseComponentIdentifier('@method')); + $this->assertSame(['signature-input', true, 'ocm'], SignatureBase::parseComponentIdentifier('signature-input;key="ocm";req')); + $this->assertSame(['signature-input', true, null], SignatureBase::parseComponentIdentifier('signature-input;req')); + $this->assertSame('"signature-input";key="ocm";req', SignatureBase::serializeComponentIdentifier('signature-input', true, 'ocm')); + } + public function testSerializeBareItemEscapesQuotes(): void { $this->assertSame('"\\"hi\\""', SignatureBase::serializeBareItem('"hi"')); $this->assertSame('"\\\\"', SignatureBase::serializeBareItem('\\'));