Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
25 changes: 25 additions & 0 deletions lib/private/OCM/OCMDiscoveryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -319,6 +321,29 @@ public function confirmRequestOrigin(?string $signedOrigin, string $ocmAddress):
}
}

/**
* @inheritDoc
*
* @template S of Http::STATUS_*
* @param S $status
* @return Response<S, array<string, mixed>>
*/
#[\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`).
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> $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))
Expand All @@ -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,
Expand Down Expand Up @@ -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(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\Security\Signature\Model;

use OC\Security\Signature\Rfc9421\Algorithm;
use OC\Security\Signature\Rfc9421\ContentDigest;
use OC\Security\Signature\Rfc9421\SignatureBase;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Response;
use OCP\IRequest;
use OCP\Security\Signature\Exceptions\IncomingRequestException;
use OCP\Security\Signature\Exceptions\SignatoryException;
use OCP\Security\Signature\Exceptions\SignatureException;
use OCP\Security\Signature\IIncomingSignedRequest;
use OCP\Security\Signature\ISignatoryManager;

/**
* RFC 9421 signed response profile used by OCM.
*
* The response is bound to the triggering request through the `;req`
* components: method, target URI, and the request's `ocm` entries of the
* Signature-Input and Signature dictionaries. The `;key="ocm"` parameter
* selects only that dictionary entry, so additional signatures on the same
* message (e.g. added by a proxy) do not break verification at the requester.
*
* The signature is computed lazily when the response is read out
* ({@see getStatus()}, {@see getHeaders()}, {@see render()}) and recomputed
* when the status or headers change afterwards, so the signature always
* matches the response that is actually sent.
*
* @template S of Http::STATUS_*
* @template-extends Response<S, array<string, mixed>>
*/
final class Rfc9421OutgoingSignedResponse extends Response {
private const COMPONENTS = [
Comment thread
mickenordin marked this conversation as resolved.
Resolved
'@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<lowercase-string, string>
*/
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<lowercase-string, string>
* @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;
}
}
Loading
Loading