| 1 |
// Copyright The Notary Project Authors. |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
// Package verifier provides an implementation of notation.Verifier interface |
| 15 |
package verifier |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"crypto/x509" |
| 20 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"net/http" |
| 24 |
"reflect" |
| 25 |
"strings" |
| 26 |
"time" |
| 27 |
|
| 28 |
"golang.org/x/mod/semver" |
| 29 |
"oras.land/oras-go/v2/content" |
| 30 |
|
| 31 |
"github.com/notaryproject/notation-core-go/revocation" |
| 32 |
"github.com/notaryproject/notation-core-go/revocation/purpose" |
| 33 |
revocationresult "github.com/notaryproject/notation-core-go/revocation/result" |
| 34 |
"github.com/notaryproject/notation-core-go/signature" |
| 35 |
nx509 "github.com/notaryproject/notation-core-go/x509" |
| 36 |
"github.com/notaryproject/notation-go" |
| 37 |
"github.com/notaryproject/notation-go/dir" |
| 38 |
"github.com/notaryproject/notation-go/internal/envelope" |
| 39 |
"github.com/notaryproject/notation-go/internal/pkix" |
| 40 |
notationsemver "github.com/notaryproject/notation-go/internal/semver" |
| 41 |
"github.com/notaryproject/notation-go/internal/slices" |
| 42 |
trustpolicyInternal "github.com/notaryproject/notation-go/internal/trustpolicy" |
| 43 |
"github.com/notaryproject/notation-go/log" |
| 44 |
"github.com/notaryproject/notation-go/plugin" |
| 45 |
"github.com/notaryproject/notation-go/verifier/trustpolicy" |
| 46 |
"github.com/notaryproject/notation-go/verifier/truststore" |
| 47 |
pluginframework "github.com/notaryproject/notation-plugin-framework-go/plugin" |
| 48 |
"github.com/notaryproject/tspclient-go" |
| 49 |
ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 50 |
) |
| 51 |
|
| 52 |
// verifier implements notation.Verifier and notation.verifySkipper |
| 53 |
type verifier struct { |
| 54 |
trustPolicyDoc *trustpolicy.Document |
| 55 |
trustStore truststore.X509TrustStore |
| 56 |
pluginManager plugin.Manager |
| 57 |
revocationClient revocation.Revocation |
| 58 |
revocationCodeSigningValidator revocation.Validator |
| 59 |
revocationTimestampingValidator revocation.Validator |
| 60 |
} |
| 61 |
|
| 62 |
// VerifierOptions specifies additional parameters that can be set when using |
| 63 |
// the NewWithOptions constructor |
| 64 |
type VerifierOptions struct { |
| 65 |
// RevocationClient is an implementation of revocation.Revocation to use for |
| 66 |
// verifying revocation of code signing certificate chain |
| 67 |
// |
| 68 |
// Deprecated: RevocationClient exists for backwards compatibility and |
| 69 |
// should not be used. To perform code signing certificate chain revocation |
| 70 |
// check, use [RevocationCodeSigningValidator]. |
| 71 |
RevocationClient revocation.Revocation |
| 72 |
|
| 73 |
// RevocationCodeSigningValidator is used for verifying revocation of |
| 74 |
// code signing certificate chain with context. |
| 75 |
RevocationCodeSigningValidator revocation.Validator |
| 76 |
|
| 77 |
// RevocationTimestampingValidator is used for verifying revocation of |
| 78 |
// timestamping certificate chain with context. |
| 79 |
RevocationTimestampingValidator revocation.Validator |
| 80 |
} |
| 81 |
|
| 82 |
// NewFromConfig returns a verifier based on local file system. |
| 83 |
func NewFromConfig() (notation.Verifier, error) { |
| 84 |
// load trust policy |
| 85 |
policyDocument, err := trustpolicy.LoadDocument() |
| 86 |
if err != nil { |
| 87 |
return nil, err |
| 88 |
} |
| 89 |
// load trust store |
| 90 |
x509TrustStore := truststore.NewX509TrustStore(dir.ConfigFS()) |
| 91 |
|
| 92 |
return New(policyDocument, x509TrustStore, plugin.NewCLIManager(dir.PluginFS())) |
| 93 |
} |
| 94 |
|
| 95 |
// New creates a new verifier given trustPolicy, trustStore and pluginManager |
| 96 |
func New(trustPolicy *trustpolicy.Document, trustStore truststore.X509TrustStore, pluginManager plugin.Manager) (notation.Verifier, error) { |
| 97 |
return NewWithOptions(trustPolicy, trustStore, pluginManager, VerifierOptions{}) |
| 98 |
} |
| 99 |
|
| 100 |
// NewWithOptions creates a new verifier given trustPolicy, trustStore, |
| 101 |
// pluginManager, and verifierOptions |
| 102 |
func NewWithOptions(trustPolicy *trustpolicy.Document, trustStore truststore.X509TrustStore, pluginManager plugin.Manager, verifierOptions VerifierOptions) (notation.Verifier, error) { |
| 103 |
if trustStore == nil { |
| 104 |
return nil, errors.New("trustStore cannot be nil") |
| 105 |
} |
| 106 |
|
| 107 |
if trustPolicy == nil { |
| 108 |
return nil, errors.New("trustPolicy cannot be nil") |
| 109 |
} |
| 110 |
|
| 111 |
if err := trustPolicy.Validate(); err != nil { |
| 112 |
return nil, err |
| 113 |
} |
| 114 |
v := &verifier{ |
| 115 |
trustPolicyDoc: trustPolicy, |
| 116 |
trustStore: trustStore, |
| 117 |
pluginManager: pluginManager, |
| 118 |
} |
| 119 |
|
| 120 |
if err := v.setRevocation(verifierOptions); err != nil { |
| 121 |
return nil, err |
| 122 |
} |
| 123 |
return v, nil |
| 124 |
} |
| 125 |
|
| 126 |
// setRevocation sets revocation validators of v |
| 127 |
func (v *verifier) setRevocation(verifierOptions VerifierOptions) error { |
| 128 |
// timestamping validator |
| 129 |
revocationTimestampingValidator := verifierOptions.RevocationTimestampingValidator |
| 130 |
var err error |
| 131 |
if revocationTimestampingValidator == nil { |
| 132 |
revocationTimestampingValidator, err = revocation.NewWithOptions(revocation.Options{ |
| 133 |
OCSPHTTPClient: &http.Client{Timeout: 2 * time.Second}, |
| 134 |
CertChainPurpose: purpose.Timestamping, |
| 135 |
}) |
| 136 |
if err != nil { |
| 137 |
return err |
| 138 |
} |
| 139 |
} |
| 140 |
v.revocationTimestampingValidator = revocationTimestampingValidator |
| 141 |
|
| 142 |
// code signing validator |
| 143 |
revocationCodeSigningValidator := verifierOptions.RevocationCodeSigningValidator |
| 144 |
if revocationCodeSigningValidator != nil { |
| 145 |
v.revocationCodeSigningValidator = revocationCodeSigningValidator |
| 146 |
return nil |
| 147 |
} |
| 148 |
revocationClient := verifierOptions.RevocationClient |
| 149 |
if revocationClient != nil { |
| 150 |
v.revocationClient = revocationClient |
| 151 |
return nil |
| 152 |
} |
| 153 |
|
| 154 |
// both RevocationCodeSigningValidator and RevocationClient are nil |
| 155 |
revocationCodeSigningValidator, err = revocation.NewWithOptions(revocation.Options{ |
| 156 |
OCSPHTTPClient: &http.Client{Timeout: 2 * time.Second}, |
| 157 |
CertChainPurpose: purpose.CodeSigning, |
| 158 |
}) |
| 159 |
if err != nil { |
| 160 |
return err |
| 161 |
} |
| 162 |
v.revocationCodeSigningValidator = revocationCodeSigningValidator |
| 163 |
return nil |
| 164 |
} |
| 165 |
|
| 166 |
// SkipVerify validates whether the verification level is skip. |
| 167 |
func (v *verifier) SkipVerify(ctx context.Context, opts notation.VerifierVerifyOptions) (bool, *trustpolicy.VerificationLevel, error) { |
| 168 |
logger := log.GetLogger(ctx) |
| 169 |
|
| 170 |
logger.Debugf("Check verification level against artifact %v", opts.ArtifactReference) |
| 171 |
trustPolicy, err := v.trustPolicyDoc.GetApplicableTrustPolicy(opts.ArtifactReference) |
| 172 |
if err != nil { |
| 173 |
return false, nil, notation.ErrorNoApplicableTrustPolicy{Msg: err.Error()} |
| 174 |
} |
| 175 |
logger.Infof("Trust policy configuration: %+v", trustPolicy) |
| 176 |
|
| 177 |
// ignore the error since we already validated the policy document |
| 178 |
verificationLevel, _ := trustPolicy.SignatureVerification.GetVerificationLevel() |
| 179 |
// verificationLevel is skip |
| 180 |
if reflect.DeepEqual(verificationLevel, trustpolicy.LevelSkip) { |
| 181 |
logger.Debug("Skipping signature verification") |
| 182 |
return true, trustpolicy.LevelSkip, nil |
| 183 |
} |
| 184 |
|
| 185 |
return false, verificationLevel, nil |
| 186 |
} |
| 187 |
|
| 188 |
// Verify verifies the signature associated the target OCI |
| 189 |
// artifact with manifest descriptor `desc`, and returns the outcome upon |
| 190 |
// successful verification. |
| 191 |
// If nil signature is present and the verification level is not 'skip', |
| 192 |
// an error will be returned. |
| 193 |
func (v *verifier) Verify(ctx context.Context, desc ocispec.Descriptor, signature []byte, opts notation.VerifierVerifyOptions) (*notation.VerificationOutcome, error) { |
| 194 |
artifactRef := opts.ArtifactReference |
| 195 |
envelopeMediaType := opts.SignatureMediaType |
| 196 |
pluginConfig := opts.PluginConfig |
| 197 |
logger := log.GetLogger(ctx) |
| 198 |
|
| 199 |
logger.Debugf("Verify signature against artifact %v referenced as %s in signature media type %v", desc.Digest, artifactRef, envelopeMediaType) |
| 200 |
if v.trustPolicyDoc == nil { |
| 201 |
return nil, errors.New("trustPolicyDoc is nil") |
| 202 |
} |
| 203 |
|
| 204 |
trustPolicy, err := v.trustPolicyDoc.GetApplicableTrustPolicy(artifactRef) |
| 205 |
if err != nil { |
| 206 |
return nil, notation.ErrorNoApplicableTrustPolicy{Msg: err.Error()} |
| 207 |
} |
| 208 |
|
| 209 |
logger.Infof("Trust policy configuration: %+v", trustPolicy) |
| 210 |
// ignore the error since we already validated the policy document |
| 211 |
verificationLevel, _ := trustPolicy.SignatureVerification.GetVerificationLevel() |
| 212 |
|
| 213 |
outcome := ¬ation.VerificationOutcome{ |
| 214 |
RawSignature: signature, |
| 215 |
VerificationLevel: verificationLevel, |
| 216 |
} |
| 217 |
// verificationLevel is skip |
| 218 |
if reflect.DeepEqual(verificationLevel, trustpolicy.LevelSkip) { |
| 219 |
logger.Debug("Skipping signature verification") |
| 220 |
return outcome, nil |
| 221 |
} |
| 222 |
err = v.processSignature(ctx, signature, envelopeMediaType, trustPolicy.Name, trustPolicy.TrustedIdentities, trustPolicy.TrustStores, trustPolicy.SignatureVerification, pluginConfig, outcome) |
| 223 |
|
| 224 |
if err != nil { |
| 225 |
outcome.Error = err |
| 226 |
return outcome, err |
| 227 |
} |
| 228 |
|
| 229 |
payload := &envelope.Payload{} |
| 230 |
err = json.Unmarshal(outcome.EnvelopeContent.Payload.Content, payload) |
| 231 |
if err != nil { |
| 232 |
logger.Error("Failed to unmarshal the payload content in the signature blob to envelope.Payload") |
| 233 |
outcome.Error = err |
| 234 |
return outcome, err |
| 235 |
} |
| 236 |
|
| 237 |
if !content.Equal(payload.TargetArtifact, desc) { |
| 238 |
logger.Infof("Target artifact in signature payload: %+v", payload.TargetArtifact) |
| 239 |
logger.Infof("Target artifact that want to be verified: %+v", desc) |
| 240 |
outcome.Error = errors.New("content descriptor mismatch") |
| 241 |
} |
| 242 |
|
| 243 |
if len(opts.UserMetadata) > 0 { |
| 244 |
err := verifyUserMetadata(logger, payload, opts.UserMetadata) |
| 245 |
if err != nil { |
| 246 |
outcome.Error = err |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
return outcome, outcome.Error |
| 251 |
} |
| 252 |
|
| 253 |
func (v *verifier) processSignature(ctx context.Context, sigBlob []byte, envelopeMediaType, policyName string, trustedIdentities, trustStores []string, signatureVerification trustpolicy.SignatureVerification, pluginConfig map[string]string, outcome *notation.VerificationOutcome) error { |
| 254 |
logger := log.GetLogger(ctx) |
| 255 |
|
| 256 |
// verify integrity first. notation will always verify integrity no matter |
| 257 |
// what the signing scheme is |
| 258 |
envContent, integrityResult := verifyIntegrity(sigBlob, envelopeMediaType, outcome) |
| 259 |
outcome.EnvelopeContent = envContent |
| 260 |
outcome.VerificationResults = append(outcome.VerificationResults, integrityResult) |
| 261 |
if integrityResult.Error != nil { |
| 262 |
logVerificationResult(logger, integrityResult) |
| 263 |
return integrityResult.Error |
| 264 |
} |
| 265 |
|
| 266 |
// check if we need to verify using a plugin |
| 267 |
var pluginCapabilities []pluginframework.Capability |
| 268 |
verificationPluginName, err := getVerificationPlugin(&outcome.EnvelopeContent.SignerInfo) |
| 269 |
// use plugin, but getPluginName returns an error |
| 270 |
if err != nil && err != errExtendedAttributeNotExist { |
| 271 |
return err |
| 272 |
} |
| 273 |
|
| 274 |
var installedPlugin pluginframework.VerifyPlugin |
| 275 |
if verificationPluginName != "" { |
| 276 |
logger.Debugf("Finding verification plugin %q", verificationPluginName) |
| 277 |
verificationPluginMinVersion, err := getVerificationPluginMinVersion(&outcome.EnvelopeContent.SignerInfo) |
| 278 |
if err != nil && err != errExtendedAttributeNotExist { |
| 279 |
return notation.ErrorVerificationInconclusive{Msg: fmt.Sprintf("error while getting plugin minimum version, error: %s", err)} |
| 280 |
} |
| 281 |
|
| 282 |
if v.pluginManager == nil { |
| 283 |
return notation.ErrorVerificationInconclusive{Msg: "plugin unsupported due to nil verifier.pluginManager"} |
| 284 |
} |
| 285 |
installedPlugin, err = v.pluginManager.Get(ctx, verificationPluginName) |
| 286 |
if err != nil { |
| 287 |
return notation.ErrorVerificationInconclusive{Msg: fmt.Sprintf("error while locating the verification plugin %q, make sure the plugin is installed successfully before verifying the signature. error: %s", verificationPluginName, err)} |
| 288 |
} |
| 289 |
|
| 290 |
// filter the "verification" capabilities supported by the installed |
| 291 |
// plugin |
| 292 |
metadata, err := installedPlugin.GetMetadata(ctx, &pluginframework.GetMetadataRequest{PluginConfig: pluginConfig}) |
| 293 |
if err != nil { |
| 294 |
return err |
| 295 |
} |
| 296 |
|
| 297 |
pluginVersion := metadata.Version |
| 298 |
|
| 299 |
//checking if the plugin version is in valid semver format |
| 300 |
if !notationsemver.IsValid(pluginVersion) { |
| 301 |
return notation.ErrorVerificationInconclusive{Msg: fmt.Sprintf("plugin %s has pluginVersion %s which is not in valid semver format", verificationPluginName, pluginVersion)} |
| 302 |
} |
| 303 |
|
| 304 |
if !isRequiredVerificationPluginVer(pluginVersion, verificationPluginMinVersion) { |
| 305 |
return notation.ErrorVerificationInconclusive{Msg: fmt.Sprintf("found plugin %s with version %s but signature verification needs plugin version greater than or equal to %s", verificationPluginName, pluginVersion, verificationPluginMinVersion)} |
| 306 |
} |
| 307 |
|
| 308 |
for _, capability := range metadata.Capabilities { |
| 309 |
if capability == pluginframework.CapabilityRevocationCheckVerifier || capability == pluginframework.CapabilityTrustedIdentityVerifier { |
| 310 |
pluginCapabilities = append(pluginCapabilities, capability) |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
if len(pluginCapabilities) == 0 { |
| 315 |
return notation.ErrorVerificationInconclusive{Msg: fmt.Sprintf("digital signature requires plugin %q with signature verification capabilities (%q and/or %q) installed", verificationPluginName, pluginframework.CapabilityTrustedIdentityVerifier, pluginframework.CapabilityRevocationCheckVerifier)} |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
// verify x509 trust store based authenticity |
| 320 |
logger.Debug("Validating cert chain") |
| 321 |
trustCerts, err := loadX509TrustStores(ctx, outcome.EnvelopeContent.SignerInfo.SignedAttributes.SigningScheme, policyName, trustStores, v.trustStore) |
| 322 |
var authenticityResult *notation.ValidationResult |
| 323 |
if err != nil { |
| 324 |
authenticityResult = ¬ation.ValidationResult{ |
| 325 |
Error: err, |
| 326 |
Type: trustpolicy.TypeAuthenticity, |
| 327 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticity], |
| 328 |
} |
| 329 |
} else { |
| 330 |
// verify authenticity |
| 331 |
authenticityResult = verifyAuthenticity(trustCerts, outcome) |
| 332 |
} |
| 333 |
outcome.VerificationResults = append(outcome.VerificationResults, authenticityResult) |
| 334 |
logVerificationResult(logger, authenticityResult) |
| 335 |
if isCriticalFailure(authenticityResult) { |
| 336 |
return authenticityResult.Error |
| 337 |
} |
| 338 |
|
| 339 |
// verify x509 trusted identity based authenticity (only if notation needs |
| 340 |
// to perform this verification rather than a plugin) |
| 341 |
if !slices.Contains(pluginCapabilities, pluginframework.CapabilityTrustedIdentityVerifier) { |
| 342 |
logger.Debug("Validating trust identity") |
| 343 |
err = verifyX509TrustedIdentities(policyName, trustedIdentities, outcome.EnvelopeContent.SignerInfo.CertificateChain) |
| 344 |
if err != nil { |
| 345 |
authenticityResult.Error = err |
| 346 |
logVerificationResult(logger, authenticityResult) |
| 347 |
} |
| 348 |
if isCriticalFailure(authenticityResult) { |
| 349 |
return authenticityResult.Error |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
// verify expiry |
| 354 |
logger.Debug("Validating expiry") |
| 355 |
expiryResult := verifyExpiry(outcome) |
| 356 |
outcome.VerificationResults = append(outcome.VerificationResults, expiryResult) |
| 357 |
logVerificationResult(logger, expiryResult) |
| 358 |
if isCriticalFailure(expiryResult) { |
| 359 |
return expiryResult.Error |
| 360 |
} |
| 361 |
|
| 362 |
// verify authentic timestamp |
| 363 |
logger.Debug("Validating authentic timestamp") |
| 364 |
authenticTimestampResult := verifyAuthenticTimestamp(ctx, policyName, trustStores, signatureVerification, v.trustStore, v.revocationTimestampingValidator, outcome) |
| 365 |
outcome.VerificationResults = append(outcome.VerificationResults, authenticTimestampResult) |
| 366 |
logVerificationResult(logger, authenticTimestampResult) |
| 367 |
if isCriticalFailure(authenticTimestampResult) { |
| 368 |
return authenticTimestampResult.Error |
| 369 |
} |
| 370 |
|
| 371 |
// verify revocation |
| 372 |
// check if we need to bypass the revocation check, since revocation can be |
| 373 |
// skipped using a trust policy or a plugin may override the check |
| 374 |
if outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation] != trustpolicy.ActionSkip && |
| 375 |
!slices.Contains(pluginCapabilities, pluginframework.CapabilityRevocationCheckVerifier) { |
| 376 |
|
| 377 |
logger.Debug("Validating revocation") |
| 378 |
revocationResult := v.verifyRevocation(ctx, outcome) |
| 379 |
outcome.VerificationResults = append(outcome.VerificationResults, revocationResult) |
| 380 |
logVerificationResult(logger, revocationResult) |
| 381 |
if isCriticalFailure(revocationResult) { |
| 382 |
return revocationResult.Error |
| 383 |
} |
| 384 |
} |
| 385 |
|
| 386 |
// perform extended verification using verification plugin if present |
| 387 |
if installedPlugin != nil { |
| 388 |
var capabilitiesToVerify []pluginframework.Capability |
| 389 |
for _, pc := range pluginCapabilities { |
| 390 |
// skip the revocation capability if the trust policy is configured |
| 391 |
// to skip it |
| 392 |
if outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation] == trustpolicy.ActionSkip && pc == pluginframework.CapabilityRevocationCheckVerifier { |
| 393 |
logger.Debugf("Skipping the %v validation", pc) |
| 394 |
continue |
| 395 |
} |
| 396 |
capabilitiesToVerify = append(capabilitiesToVerify, pc) |
| 397 |
} |
| 398 |
|
| 399 |
if len(capabilitiesToVerify) > 0 { |
| 400 |
logger.Debugf("Executing verification plugin %q with capabilities %v", verificationPluginName, capabilitiesToVerify) |
| 401 |
response, err := executePlugin(ctx, installedPlugin, capabilitiesToVerify, outcome.EnvelopeContent, trustedIdentities, pluginConfig) |
| 402 |
if err != nil { |
| 403 |
return fmt.Errorf("failed to verify with plugin %s: %w", verificationPluginName, err) |
| 404 |
} |
| 405 |
|
| 406 |
return processPluginResponse(capabilitiesToVerify, response, outcome) |
| 407 |
} |
| 408 |
} |
| 409 |
return nil |
| 410 |
} |
| 411 |
|
| 412 |
func (v *verifier) verifyRevocation(ctx context.Context, outcome *notation.VerificationOutcome) *notation.ValidationResult { |
| 413 |
logger := log.GetLogger(ctx) |
| 414 |
|
| 415 |
if v.revocationCodeSigningValidator == nil && v.revocationClient == nil { |
| 416 |
return ¬ation.ValidationResult{ |
| 417 |
Type: trustpolicy.TypeRevocation, |
| 418 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation], |
| 419 |
Error: fmt.Errorf("unable to check revocation status, code signing revocation validator cannot be nil"), |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
var authenticSigningTime time.Time |
| 424 |
if outcome.EnvelopeContent.SignerInfo.SignedAttributes.SigningScheme == signature.SigningSchemeX509SigningAuthority { |
| 425 |
authenticSigningTime, _ = outcome.EnvelopeContent.SignerInfo.AuthenticSigningTime() |
| 426 |
} |
| 427 |
|
| 428 |
var certResults []*revocationresult.CertRevocationResult |
| 429 |
var err error |
| 430 |
if v.revocationCodeSigningValidator != nil { |
| 431 |
certResults, err = v.revocationCodeSigningValidator.ValidateContext(ctx, revocation.ValidateContextOptions{ |
| 432 |
CertChain: outcome.EnvelopeContent.SignerInfo.CertificateChain, |
| 433 |
AuthenticSigningTime: authenticSigningTime, |
| 434 |
}) |
| 435 |
} else { |
| 436 |
certResults, err = v.revocationClient.Validate(outcome.EnvelopeContent.SignerInfo.CertificateChain, authenticSigningTime) |
| 437 |
} |
| 438 |
if err != nil { |
| 439 |
logger.Debug("Error while checking revocation status, err: %s", err.Error()) |
| 440 |
return ¬ation.ValidationResult{ |
| 441 |
Type: trustpolicy.TypeRevocation, |
| 442 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation], |
| 443 |
Error: fmt.Errorf("unable to check revocation status, err: %s", err.Error()), |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
result := ¬ation.ValidationResult{ |
| 448 |
Type: trustpolicy.TypeRevocation, |
| 449 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation], |
| 450 |
} |
| 451 |
finalResult, problematicCertSubject := revocationFinalResult(certResults, outcome.EnvelopeContent.SignerInfo.CertificateChain, logger) |
| 452 |
switch finalResult { |
| 453 |
case revocationresult.ResultOK: |
| 454 |
logger.Debug("No verification impacting errors encountered while checking revocation, status is OK") |
| 455 |
case revocationresult.ResultRevoked: |
| 456 |
result.Error = fmt.Errorf("signing certificate with subject %q is revoked", problematicCertSubject) |
| 457 |
default: |
| 458 |
// revocationresult.ResultUnknown |
| 459 |
result.Error = fmt.Errorf("signing certificate with subject %q revocation status is unknown", problematicCertSubject) |
| 460 |
} |
| 461 |
|
| 462 |
return result |
| 463 |
} |
| 464 |
|
| 465 |
func processPluginResponse(capabilitiesToVerify []pluginframework.Capability, response *pluginframework.VerifySignatureResponse, outcome *notation.VerificationOutcome) error { |
| 466 |
verificationPluginName, err := getVerificationPlugin(&outcome.EnvelopeContent.SignerInfo) |
| 467 |
if err != nil { |
| 468 |
return err |
| 469 |
} |
| 470 |
|
| 471 |
// verify all extended critical attributes are processed by the plugin |
| 472 |
for _, attr := range getNonPluginExtendedCriticalAttributes(&outcome.EnvelopeContent.SignerInfo) { |
| 473 |
if !slices.ContainsAny(response.ProcessedAttributes, attr.Key) { |
| 474 |
return fmt.Errorf("extended critical attribute %q was not processed by the verification plugin %q (all extended critical attributes must be processed by the verification plugin)", attr.Key, verificationPluginName) |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
for _, capability := range capabilitiesToVerify { |
| 479 |
pluginResult := response.VerificationResults[capability] |
| 480 |
if pluginResult == nil { |
| 481 |
// verification result is empty for this capability |
| 482 |
return notation.ErrorVerificationInconclusive{Msg: fmt.Sprintf("verification plugin %q failed to verify %q", verificationPluginName, capability)} |
| 483 |
} |
| 484 |
switch capability { |
| 485 |
case pluginframework.CapabilityTrustedIdentityVerifier: |
| 486 |
if !pluginResult.Success { |
| 487 |
// find the Authenticity VerificationResult that we already |
| 488 |
// created during x509 trust store verification |
| 489 |
var authenticityResult *notation.ValidationResult |
| 490 |
for _, r := range outcome.VerificationResults { |
| 491 |
if r.Type == trustpolicy.TypeAuthenticity { |
| 492 |
authenticityResult = r |
| 493 |
break |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
authenticityResult.Error = fmt.Errorf("trusted identify verification by plugin %q failed with reason %q", verificationPluginName, pluginResult.Reason) |
| 498 |
|
| 499 |
if isCriticalFailure(authenticityResult) { |
| 500 |
return authenticityResult.Error |
| 501 |
} |
| 502 |
} |
| 503 |
case pluginframework.CapabilityRevocationCheckVerifier: |
| 504 |
var revocationResult *notation.ValidationResult |
| 505 |
if !pluginResult.Success { |
| 506 |
revocationResult = ¬ation.ValidationResult{ |
| 507 |
Error: fmt.Errorf("revocation check by verification plugin %q failed with reason %q", verificationPluginName, pluginResult.Reason), |
| 508 |
Type: trustpolicy.TypeRevocation, |
| 509 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation], |
| 510 |
} |
| 511 |
} else { |
| 512 |
revocationResult = ¬ation.ValidationResult{ |
| 513 |
Type: trustpolicy.TypeRevocation, |
| 514 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeRevocation], |
| 515 |
} |
| 516 |
} |
| 517 |
outcome.VerificationResults = append(outcome.VerificationResults, revocationResult) |
| 518 |
if isCriticalFailure(revocationResult) { |
| 519 |
return revocationResult.Error |
| 520 |
} |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
return nil |
| 525 |
} |
| 526 |
|
| 527 |
func verifyIntegrity(sigBlob []byte, envelopeMediaType string, outcome *notation.VerificationOutcome) (*signature.EnvelopeContent, *notation.ValidationResult) { |
| 528 |
// parse the signature |
| 529 |
sigEnv, err := signature.ParseEnvelope(envelopeMediaType, sigBlob) |
| 530 |
if err != nil { |
| 531 |
return nil, ¬ation.ValidationResult{ |
| 532 |
Error: fmt.Errorf("unable to parse the digital signature, error : %s", err), |
| 533 |
Type: trustpolicy.TypeIntegrity, |
| 534 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeIntegrity], |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
// verify integrity |
| 539 |
envContent, err := sigEnv.Verify() |
| 540 |
if err != nil { |
| 541 |
switch err.(type) { |
| 542 |
case *signature.SignatureEnvelopeNotFoundError, *signature.InvalidSignatureError, *signature.SignatureIntegrityError: |
| 543 |
return nil, ¬ation.ValidationResult{ |
| 544 |
Error: err, |
| 545 |
Type: trustpolicy.TypeIntegrity, |
| 546 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeIntegrity], |
| 547 |
} |
| 548 |
default: |
| 549 |
// unexpected error |
| 550 |
return nil, ¬ation.ValidationResult{ |
| 551 |
Error: notation.ErrorVerificationInconclusive{Msg: err.Error()}, |
| 552 |
Type: trustpolicy.TypeIntegrity, |
| 553 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeIntegrity], |
| 554 |
} |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
if err := envelope.ValidatePayloadContentType(&envContent.Payload); err != nil { |
| 559 |
return nil, ¬ation.ValidationResult{ |
| 560 |
Error: err, |
| 561 |
Type: trustpolicy.TypeIntegrity, |
| 562 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeIntegrity], |
| 563 |
} |
| 564 |
} |
| 565 |
|
| 566 |
// integrity has been verified successfully |
| 567 |
return envContent, ¬ation.ValidationResult{ |
| 568 |
Type: trustpolicy.TypeIntegrity, |
| 569 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeIntegrity], |
| 570 |
} |
| 571 |
} |
| 572 |
|
| 573 |
func verifyAuthenticity(trustCerts []*x509.Certificate, outcome *notation.VerificationOutcome) *notation.ValidationResult { |
| 574 |
if len(trustCerts) < 1 { |
| 575 |
return ¬ation.ValidationResult{ |
| 576 |
Error: notation.ErrorVerificationInconclusive{Msg: "no trusted certificates are found to verify authenticity"}, |
| 577 |
Type: trustpolicy.TypeAuthenticity, |
| 578 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticity], |
| 579 |
} |
| 580 |
} |
| 581 |
_, err := signature.VerifyAuthenticity(&outcome.EnvelopeContent.SignerInfo, trustCerts) |
| 582 |
if err != nil { |
| 583 |
switch err.(type) { |
| 584 |
case *signature.SignatureAuthenticityError: |
| 585 |
return ¬ation.ValidationResult{ |
| 586 |
Error: err, |
| 587 |
Type: trustpolicy.TypeAuthenticity, |
| 588 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticity], |
| 589 |
} |
| 590 |
default: |
| 591 |
return ¬ation.ValidationResult{ |
| 592 |
Error: notation.ErrorVerificationInconclusive{Msg: "authenticity verification failed with error : " + err.Error()}, |
| 593 |
Type: trustpolicy.TypeAuthenticity, |
| 594 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticity], |
| 595 |
} |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
return ¬ation.ValidationResult{ |
| 600 |
Type: trustpolicy.TypeAuthenticity, |
| 601 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticity], |
| 602 |
} |
| 603 |
} |
| 604 |
|
| 605 |
func verifyUserMetadata(logger log.Logger, payload *envelope.Payload, userMetadata map[string]string) error { |
| 606 |
logger.Debugf("Verifying that metadata %v is present in signature", userMetadata) |
| 607 |
logger.Debugf("Signature metadata: %v", payload.TargetArtifact.Annotations) |
| 608 |
|
| 609 |
for k, v := range userMetadata { |
| 610 |
if got, ok := payload.TargetArtifact.Annotations[k]; !ok || got != v { |
| 611 |
logger.Errorf("User required metadata %s=%s is not present in the signature", k, v) |
| 612 |
return notation.ErrorUserMetadataVerificationFailed{} |
| 613 |
} |
| 614 |
} |
| 615 |
|
| 616 |
return nil |
| 617 |
} |
| 618 |
|
| 619 |
func verifyExpiry(outcome *notation.VerificationOutcome) *notation.ValidationResult { |
| 620 |
if expiry := outcome.EnvelopeContent.SignerInfo.SignedAttributes.Expiry; !expiry.IsZero() && !time.Now().Before(expiry) { |
| 621 |
return ¬ation.ValidationResult{ |
| 622 |
Error: fmt.Errorf("digital signature has expired on %q", expiry.Format(time.RFC1123Z)), |
| 623 |
Type: trustpolicy.TypeExpiry, |
| 624 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeExpiry], |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
return ¬ation.ValidationResult{ |
| 629 |
Type: trustpolicy.TypeExpiry, |
| 630 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeExpiry], |
| 631 |
} |
| 632 |
} |
| 633 |
|
| 634 |
func verifyAuthenticTimestamp(ctx context.Context, policyName string, trustStores []string, signatureVerification trustpolicy.SignatureVerification, x509TrustStore truststore.X509TrustStore, r revocation.Validator, outcome *notation.VerificationOutcome) *notation.ValidationResult { |
| 635 |
logger := log.GetLogger(ctx) |
| 636 |
|
| 637 |
signerInfo := outcome.EnvelopeContent.SignerInfo |
| 638 |
// under signing scheme notary.x509 |
| 639 |
if signerInfo.SignedAttributes.SigningScheme == signature.SigningSchemeX509 { |
| 640 |
logger.Debug("Under signing scheme notary.x509...") |
| 641 |
return ¬ation.ValidationResult{ |
| 642 |
Error: verifyTimestamp(ctx, policyName, trustStores, signatureVerification, x509TrustStore, r, outcome), |
| 643 |
Type: trustpolicy.TypeAuthenticTimestamp, |
| 644 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticTimestamp], |
| 645 |
} |
| 646 |
} |
| 647 |
|
| 648 |
// under signing scheme notary.x509.signingAuthority |
| 649 |
logger.Debug("Under signing scheme notary.x509.signingAuthority...") |
| 650 |
authenticSigningTime := signerInfo.SignedAttributes.SigningTime |
| 651 |
for _, cert := range signerInfo.CertificateChain { |
| 652 |
if authenticSigningTime.Before(cert.NotBefore) || authenticSigningTime.After(cert.NotAfter) { |
| 653 |
return ¬ation.ValidationResult{ |
| 654 |
Error: fmt.Errorf("certificate %q was not valid when the digital signature was produced at %q", cert.Subject, authenticSigningTime.Format(time.RFC1123Z)), |
| 655 |
Type: trustpolicy.TypeAuthenticTimestamp, |
| 656 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticTimestamp], |
| 657 |
} |
| 658 |
} |
| 659 |
} |
| 660 |
|
| 661 |
// success |
| 662 |
return ¬ation.ValidationResult{ |
| 663 |
Type: trustpolicy.TypeAuthenticTimestamp, |
| 664 |
Action: outcome.VerificationLevel.Enforcement[trustpolicy.TypeAuthenticTimestamp], |
| 665 |
} |
| 666 |
} |
| 667 |
|
| 668 |
// revocationFinalResult returns the final revocation result and problematic |
| 669 |
// certificate subject if the final result is not ResultOK |
| 670 |
func revocationFinalResult(certResults []*revocationresult.CertRevocationResult, certChain []*x509.Certificate, logger log.Logger) (revocationresult.Result, string) { |
| 671 |
finalResult := revocationresult.ResultUnknown |
| 672 |
numOKResults := 0 |
| 673 |
var problematicCertSubject string |
| 674 |
revokedFound := false |
| 675 |
var revokedCertSubject string |
| 676 |
for i := len(certResults) - 1; i >= 0; i-- { |
| 677 |
cert := certChain[i] |
| 678 |
certResult := certResults[i] |
| 679 |
if certResult.RevocationMethod == revocationresult.RevocationMethodOCSPFallbackCRL { |
| 680 |
// log the fallback warning |
| 681 |
logger.Warnf("OCSP check failed with unknown error and fallback to CRL check for certificate #%d in chain with subject %q", (i + 1), cert.Subject) |
| 682 |
} |
| 683 |
for _, serverResult := range certResult.ServerResults { |
| 684 |
if serverResult.Error != nil { |
| 685 |
// log individual server errors |
| 686 |
if certResult.RevocationMethod == revocationresult.RevocationMethodOCSPFallbackCRL && serverResult.RevocationMethod == revocationresult.RevocationMethodOCSP { |
| 687 |
// when the final revocation method is OCSPFallbackCRL, |
| 688 |
// the OCSP server results should not be logged as an error |
| 689 |
// since the CRL revocation check can succeed. |
| 690 |
logger.Debugf("Certificate #%d in chain with subject %q encountered an error for revocation method %s at URL %q: %v", (i + 1), cert.Subject, revocationresult.RevocationMethodOCSP, serverResult.Server, serverResult.Error) |
| 691 |
continue |
| 692 |
} |
| 693 |
logger.Errorf("Certificate #%d in chain with subject %q encountered an error for revocation method %s at URL %q: %v", (i + 1), cert.Subject, serverResult.RevocationMethod, serverResult.Server, serverResult.Error) |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
if certResult.Result == revocationresult.ResultOK || certResult.Result == revocationresult.ResultNonRevokable { |
| 698 |
numOKResults++ |
| 699 |
} else { |
| 700 |
finalResult = certResult.Result |
| 701 |
problematicCertSubject = cert.Subject.String() |
| 702 |
if certResult.Result == revocationresult.ResultRevoked { |
| 703 |
revokedFound = true |
| 704 |
revokedCertSubject = problematicCertSubject |
| 705 |
} |
| 706 |
} |
| 707 |
|
| 708 |
if i < len(certResults)-1 && certResult.Result == revocationresult.ResultNonRevokable { |
| 709 |
logger.Warnf("Certificate #%d in the chain with subject %q neither has an OCSP nor a CRL revocation method.", (i + 1), cert.Subject) |
| 710 |
} |
| 711 |
} |
| 712 |
if revokedFound { |
| 713 |
problematicCertSubject = revokedCertSubject |
| 714 |
finalResult = revocationresult.ResultRevoked |
| 715 |
} |
| 716 |
if numOKResults == len(certResults) { |
| 717 |
finalResult = revocationresult.ResultOK |
| 718 |
} |
| 719 |
return finalResult, problematicCertSubject |
| 720 |
} |
| 721 |
|
| 722 |
func executePlugin(ctx context.Context, installedPlugin pluginframework.VerifyPlugin, capabilitiesToVerify []pluginframework.Capability, envelopeContent *signature.EnvelopeContent, trustedIdentities []string, pluginConfig map[string]string) (*pluginframework.VerifySignatureResponse, error) { |
| 723 |
logger := log.GetLogger(ctx) |
| 724 |
// sanity check |
| 725 |
if installedPlugin == nil { |
| 726 |
return nil, errors.New("installedPlugin cannot be nil") |
| 727 |
} |
| 728 |
|
| 729 |
signerInfo, payloadInfo := &envelopeContent.SignerInfo, envelopeContent.Payload |
| 730 |
var attributesToProcess []string |
| 731 |
extendedAttributes := make(map[string]interface{}) |
| 732 |
|
| 733 |
for _, attr := range getNonPluginExtendedCriticalAttributes(signerInfo) { |
| 734 |
extendedAttributes[attr.Key.(string)] = attr.Value |
| 735 |
attributesToProcess = append(attributesToProcess, attr.Key.(string)) |
| 736 |
} |
| 737 |
logger.Debugf("Added plugin attributes to be processed %v", attributesToProcess) |
| 738 |
|
| 739 |
var certChain [][]byte |
| 740 |
for _, cert := range signerInfo.CertificateChain { |
| 741 |
certChain = append(certChain, cert.Raw) |
| 742 |
} |
| 743 |
var authenticSigningTime *time.Time |
| 744 |
if signerInfo.SignedAttributes.SigningScheme == signature.SigningSchemeX509SigningAuthority { |
| 745 |
authenticSigningTime = &signerInfo.SignedAttributes.SigningTime |
| 746 |
// TODO use authenticSigningTime from signerInfo |
| 747 |
// https://github.com/notaryproject/notation-core-go/issues/38 |
| 748 |
} |
| 749 |
|
| 750 |
sig := pluginframework.Signature{ |
| 751 |
CriticalAttributes: pluginframework.CriticalAttributes{ |
| 752 |
ContentType: payloadInfo.ContentType, |
| 753 |
SigningScheme: string(signerInfo.SignedAttributes.SigningScheme), |
| 754 |
Expiry: &signerInfo.SignedAttributes.Expiry, |
| 755 |
AuthenticSigningTime: authenticSigningTime, |
| 756 |
ExtendedAttributes: extendedAttributes, |
| 757 |
}, |
| 758 |
UnprocessedAttributes: attributesToProcess, |
| 759 |
CertificateChain: certChain, |
| 760 |
} |
| 761 |
|
| 762 |
policy := pluginframework.TrustPolicy{ |
| 763 |
TrustedIdentities: trustedIdentities, |
| 764 |
SignatureVerification: capabilitiesToVerify, |
| 765 |
} |
| 766 |
|
| 767 |
req := &pluginframework.VerifySignatureRequest{ |
| 768 |
ContractVersion: pluginframework.ContractVersion, |
| 769 |
Signature: sig, |
| 770 |
TrustPolicy: policy, |
| 771 |
PluginConfig: pluginConfig, |
| 772 |
} |
| 773 |
return installedPlugin.VerifySignature(ctx, req) |
| 774 |
} |
| 775 |
|
| 776 |
func verifyX509TrustedIdentities(policyName string, trustedIdentities []string, certs []*x509.Certificate) error { |
| 777 |
if slices.Contains(trustedIdentities, trustpolicyInternal.Wildcard) { |
| 778 |
return nil |
| 779 |
} |
| 780 |
|
| 781 |
var trustedX509Identities []map[string]string |
| 782 |
for _, identity := range trustedIdentities { |
| 783 |
identityPrefix, identityValue, found := strings.Cut(identity, ":") |
| 784 |
if !found { |
| 785 |
return fmt.Errorf("trust policy statement %q has trusted identity %q missing separator", policyName, identity) |
| 786 |
} |
| 787 |
|
| 788 |
// notation natively supports x509.subject identities only |
| 789 |
if identityPrefix == trustpolicyInternal.X509Subject { |
| 790 |
// identityValue cannot be empty |
| 791 |
if identityValue == "" { |
| 792 |
return fmt.Errorf("trust policy statement %q has trusted identity %q without an identity value", policyName, identity) |
| 793 |
} |
| 794 |
parsedSubject, err := pkix.ParseDistinguishedName(identityValue) |
| 795 |
if err != nil { |
| 796 |
return err |
| 797 |
} |
| 798 |
trustedX509Identities = append(trustedX509Identities, parsedSubject) |
| 799 |
} |
| 800 |
} |
| 801 |
|
| 802 |
if len(trustedX509Identities) == 0 { |
| 803 |
return fmt.Errorf("no x509 trusted identities are configured in the trust policy %q", policyName) |
| 804 |
} |
| 805 |
|
| 806 |
leafCert := certs[0] // trusted identities only supported on the leaf cert |
| 807 |
|
| 808 |
// parse the certificate subject following rfc 4514 DN syntax |
| 809 |
leafCertDN, err := pkix.ParseDistinguishedName(leafCert.Subject.String()) |
| 810 |
if err != nil { |
| 811 |
return fmt.Errorf("error while parsing the certificate subject from the digital signature. error : %q", err) |
| 812 |
} |
| 813 |
for _, trustedX509Identity := range trustedX509Identities { |
| 814 |
if pkix.IsSubsetDN(trustedX509Identity, leafCertDN) { |
| 815 |
return nil |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
return fmt.Errorf("signing certificate from the digital signature does not match the X.509 trusted identities %q defined in the trust policy %q", trustedX509Identities, policyName) |
| 820 |
} |
| 821 |
|
| 822 |
func logVerificationResult(logger log.Logger, result *notation.ValidationResult) { |
| 823 |
if result.Error == nil { |
| 824 |
return |
| 825 |
} |
| 826 |
switch result.Action { |
| 827 |
case trustpolicy.ActionLog: |
| 828 |
logger.Warnf("%v validation failed with validation action set to \"logged\". Failure reason: %v", result.Type, result.Error) |
| 829 |
case trustpolicy.ActionEnforce: |
| 830 |
logger.Errorf("%v validation failed. Failure reason: %v", result.Type, result.Error) |
| 831 |
} |
| 832 |
} |
| 833 |
|
| 834 |
func isRequiredVerificationPluginVer(pluginVer string, minPluginVer string) bool { |
| 835 |
return semver.Compare("v"+pluginVer, "v"+minPluginVer) != -1 |
| 836 |
} |
| 837 |
|
| 838 |
// verifyTimestamp provides core verification logic of authentic timestamp under |
| 839 |
// signing scheme `notary.x509`. |
| 840 |
func verifyTimestamp(ctx context.Context, policyName string, trustStores []string, signatureVerification trustpolicy.SignatureVerification, x509TrustStore truststore.X509TrustStore, r revocation.Validator, outcome *notation.VerificationOutcome) error { |
| 841 |
logger := log.GetLogger(ctx) |
| 842 |
|
| 843 |
signerInfo := outcome.EnvelopeContent.SignerInfo |
| 844 |
performTimestampVerification := true |
| 845 |
|
| 846 |
// check if tsa trust store is configured in trust policy |
| 847 |
tsaEnabled, err := isTSATrustStoreInPolicy(policyName, trustStores) |
| 848 |
if err != nil { |
| 849 |
return fmt.Errorf("failed to check tsa trust store configuration in turst policy with error: %w", err) |
| 850 |
} |
| 851 |
if !tsaEnabled { |
| 852 |
logger.Info("Timestamp verification disabled: no tsa trust store is configured in trust policy") |
| 853 |
performTimestampVerification = false |
| 854 |
} |
| 855 |
|
| 856 |
// check based on 'verifyTimestamp' field |
| 857 |
timeOfVerification := time.Now() |
| 858 |
if performTimestampVerification && |
| 859 |
signatureVerification.VerifyTimestamp == trustpolicy.OptionAfterCertExpiry { |
| 860 |
// check if signing cert chain has expired |
| 861 |
var expired bool |
| 862 |
for _, cert := range signerInfo.CertificateChain { |
| 863 |
if timeOfVerification.After(cert.NotAfter) { |
| 864 |
expired = true |
| 865 |
break |
| 866 |
} |
| 867 |
} |
| 868 |
if !expired { |
| 869 |
logger.Infof("Timestamp verification disabled: verifyTimestamp is set to %q and signing cert chain unexpired", trustpolicy.OptionAfterCertExpiry) |
| 870 |
performTimestampVerification = false |
| 871 |
} |
| 872 |
} |
| 873 |
|
| 874 |
// timestamp verification disabled, signing cert chain MUST be valid |
| 875 |
// at time of verification |
| 876 |
if !performTimestampVerification { |
| 877 |
for _, cert := range signerInfo.CertificateChain { |
| 878 |
if timeOfVerification.Before(cert.NotBefore) { |
| 879 |
return fmt.Errorf("verification time is before certificate %q validity period, it will be valid from %q", cert.Subject, cert.NotBefore.Format(time.RFC1123Z)) |
| 880 |
} |
| 881 |
if timeOfVerification.After(cert.NotAfter) { |
| 882 |
return fmt.Errorf("verification time is after certificate %q validity period, it was expired at %q", cert.Subject, cert.NotAfter.Format(time.RFC1123Z)) |
| 883 |
} |
| 884 |
} |
| 885 |
|
| 886 |
// success |
| 887 |
return nil |
| 888 |
} |
| 889 |
|
| 890 |
// Performing timestamp verification |
| 891 |
logger.Debug("Performing timestamp verification...") |
| 892 |
|
| 893 |
// 1. Timestamp countersignature MUST be present |
| 894 |
logger.Debug("Checking timestamp countersignature existence...") |
| 895 |
if len(signerInfo.UnsignedAttributes.TimestampSignature) == 0 { |
| 896 |
return errors.New("no timestamp countersignature was found in the signature envelope") |
| 897 |
} |
| 898 |
|
| 899 |
// 2. Verify the timestamp countersignature |
| 900 |
logger.Debug("Verifying the timestamp countersignature...") |
| 901 |
signedToken, err := tspclient.ParseSignedToken(signerInfo.UnsignedAttributes.TimestampSignature) |
| 902 |
if err != nil { |
| 903 |
return fmt.Errorf("failed to parse timestamp countersignature with error: %w", err) |
| 904 |
} |
| 905 |
info, err := signedToken.Info() |
| 906 |
if err != nil { |
| 907 |
return fmt.Errorf("failed to get the timestamp TSTInfo with error: %w", err) |
| 908 |
} |
| 909 |
timestamp, err := info.Validate(signerInfo.Signature) |
| 910 |
if err != nil { |
| 911 |
return fmt.Errorf("failed to get timestamp from timestamp countersignature with error: %w", err) |
| 912 |
} |
| 913 |
trustTSACerts, err := loadX509TSATrustStores(ctx, outcome.EnvelopeContent.SignerInfo.SignedAttributes.SigningScheme, policyName, trustStores, x509TrustStore) |
| 914 |
if err != nil { |
| 915 |
return fmt.Errorf("failed to load tsa trust store with error: %w", err) |
| 916 |
} |
| 917 |
if len(trustTSACerts) == 0 { |
| 918 |
return errors.New("no trusted TSA certificate found in trust store") |
| 919 |
} |
| 920 |
rootCertPool := x509.NewCertPool() |
| 921 |
for _, trustedCerts := range trustTSACerts { |
| 922 |
rootCertPool.AddCert(trustedCerts) |
| 923 |
} |
| 924 |
tsaCertChain, err := signedToken.Verify(ctx, x509.VerifyOptions{ |
| 925 |
CurrentTime: timestamp.Value, |
| 926 |
Roots: rootCertPool, |
| 927 |
}) |
| 928 |
if err != nil { |
| 929 |
return fmt.Errorf("failed to verify the timestamp countersignature with error: %w", err) |
| 930 |
} |
| 931 |
|
| 932 |
// 3. Validate timestamping certificate chain |
| 933 |
logger.Debug("Validating timestamping certificate chain...") |
| 934 |
if err := nx509.ValidateTimestampingCertChain(tsaCertChain); err != nil { |
| 935 |
return fmt.Errorf("failed to validate the timestamping certificate chain with error: %w", err) |
| 936 |
} |
| 937 |
logger.Debug("The subject of TSA signing certificate is: ", tsaCertChain[0].Subject) |
| 938 |
|
| 939 |
// 4. Check the timestamp against the signing certificate chain |
| 940 |
logger.Debug("Checking the timestamp against the signing certificate chain...") |
| 941 |
logger.Debugf("Timestamp range: %s", timestamp.Format(time.RFC3339)) |
| 942 |
for _, cert := range signerInfo.CertificateChain { |
| 943 |
if !timestamp.BoundedAfter(cert.NotBefore) { |
| 944 |
return fmt.Errorf("timestamp can be before certificate %q validity period, it will be valid from %q", cert.Subject, cert.NotBefore.Format(time.RFC1123Z)) |
| 945 |
} |
| 946 |
if !timestamp.BoundedBefore(cert.NotAfter) { |
| 947 |
return fmt.Errorf("timestamp can be after certificate %q validity period, it was expired at %q", cert.Subject, cert.NotAfter.Format(time.RFC1123Z)) |
| 948 |
} |
| 949 |
if timeOfVerification.After(cert.NotAfter) { |
| 950 |
logger.Debugf("Certificate %q expired at %q, but timestamp is within certificate validity period", cert.Subject, cert.NotAfter.Format(time.RFC1123Z)) |
| 951 |
} |
| 952 |
} |
| 953 |
|
| 954 |
// 5. Perform the timestamping certificate chain revocation check |
| 955 |
logger.Debug("Checking timestamping certificate chain revocation...") |
| 956 |
certResults, err := r.ValidateContext(ctx, revocation.ValidateContextOptions{ |
| 957 |
CertChain: tsaCertChain, |
| 958 |
}) |
| 959 |
if err != nil { |
| 960 |
return fmt.Errorf("failed to check timestamping certificate chain revocation with error: %w", err) |
| 961 |
} |
| 962 |
finalResult, problematicCertSubject := revocationFinalResult(certResults, tsaCertChain, logger) |
| 963 |
switch finalResult { |
| 964 |
case revocationresult.ResultOK: |
| 965 |
logger.Debug("No verification impacting errors encountered while checking timestamping certificate chain revocation, status is OK") |
| 966 |
case revocationresult.ResultRevoked: |
| 967 |
return fmt.Errorf("timestamping certificate with subject %q is revoked", problematicCertSubject) |
| 968 |
default: |
| 969 |
// revocationresult.ResultUnknown |
| 970 |
return fmt.Errorf("timestamping certificate with subject %q revocation status is unknown", problematicCertSubject) |
| 971 |
} |
| 972 |
|
| 973 |
// success |
| 974 |
logger.Debug("Timestamp verification: Success") |
| 975 |
return nil |
| 976 |
} |