github.com/jasoet/gopki@v1.15.0/signing/verifier.go (about) 1 package signing 2 3 import ( 4 "crypto" 5 "crypto/ecdsa" 6 "crypto/ed25519" 7 "crypto/rsa" 8 "crypto/x509" 9 "fmt" 10 "time" 11 12 internalcrypto "github.com/jasoet/gopki/internal/crypto" 13 "github.com/smallstep/pkcs7" 14 ) 15 16 // VerifySignature verifies a signature against the original data. 17 // This is the primary function for signature verification, providing comprehensive 18 // validation of both the cryptographic signature and certificate properties. 19 // 20 // The function performs the following validation steps: 21 // 1. Certificate validity period check (unless skipped) 22 // 2. Certificate key usage validation 23 // 3. Certificate extended key usage validation 24 // 4. Certificate chain verification (if enabled) 25 // 5. Cryptographic signature verification 26 // 27 // Supported signature algorithms: 28 // - RSA with PKCS#1 v1.5 padding 29 // - ECDSA with ASN.1 DER encoding 30 // - Ed25519 with native format 31 // 32 // Parameters: 33 // - data: The original data that was signed 34 // - signature: The signature to verify (must contain certificate) 35 // - opts: Verification options controlling validation behavior 36 // 37 // Returns nil if the signature is valid and all checks pass, 38 // or an error describing the validation failure. 39 // 40 // Common verification failures: 41 // - ErrCertificateExpired: Certificate validity period has expired 42 // - ErrCertificateNotYetValid: Certificate validity period has not started 43 // - ErrVerificationFailed: Cryptographic signature verification failed 44 // - ErrMissingCertificate: No certificate provided in signature 45 // 46 // Example: 47 // 48 // opts := DefaultVerifyOptions() 49 // opts.VerifyChain = true 50 // opts.Roots = trustedRootCerts 51 // 52 // err := VerifySignature(originalData, signature, opts) 53 // if err != nil { 54 // log.Printf("Signature verification failed: %v", err) 55 // return 56 // } 57 // 58 // fmt.Println("Signature is valid and trusted") 59 func VerifySignature(data []byte, signature *Signature, opts VerifyOptions) error { 60 if signature == nil { 61 return fmt.Errorf("signature is nil") 62 } 63 64 if signature.Certificate == nil { 65 return ErrMissingCertificate 66 } 67 68 // Verify certificate validity period 69 now := opts.VerifyTime 70 if now.IsZero() { 71 now = time.Now() 72 } 73 74 if now.Before(signature.Certificate.NotBefore) { 75 return ErrCertificateNotYetValid 76 } 77 78 if now.After(signature.Certificate.NotAfter) { 79 return ErrCertificateExpired 80 } 81 82 // Check key usage if specified 83 if opts.RequiredKeyUsage != 0 { 84 if signature.Certificate.KeyUsage&opts.RequiredKeyUsage == 0 { 85 return fmt.Errorf("certificate does not have required key usage") 86 } 87 } 88 89 // Check extended key usage if specified 90 if len(opts.RequiredExtKeyUsage) > 0 { 91 hasRequiredUsage := false 92 for _, required := range opts.RequiredExtKeyUsage { 93 for _, usage := range signature.Certificate.ExtKeyUsage { 94 if usage == required { 95 hasRequiredUsage = true 96 break 97 } 98 } 99 if hasRequiredUsage { 100 break 101 } 102 } 103 if !hasRequiredUsage { 104 return fmt.Errorf("certificate does not have required extended key usage") 105 } 106 } 107 108 // Verify certificate chain if requested 109 if opts.VerifyChain { 110 if err := verifyCertificateChain(signature.Certificate, signature.CertificateChain, opts); err != nil { 111 return fmt.Errorf("certificate chain verification failed: %w", err) 112 } 113 } 114 115 // Use PKCS#7 verification for all algorithms including Ed25519 116 switch signature.Format { 117 case FormatPKCS7, FormatPKCS7Detached: 118 // Check if this is an Ed25519 PKCS#7 signature (RFC 8419 ASN.1 format) 119 if isEd25519, err := internalcrypto.IsEd25519PKCS7(signature.Data); err == nil && isEd25519 { 120 // Use RFC 8419 Ed25519 PKCS#7 verification 121 return verifyEd25519PKCS7Signature(data, signature) 122 } 123 // Use standard PKCS#7 verification for RSA and ECDSA 124 return verifyPKCS7SignatureFormat(data, signature, opts) 125 default: 126 return fmt.Errorf("unsupported signature format: %s", signature.Format) 127 } 128 } 129 130 // VerifyWithCertificate verifies a signature using a specific certificate. 131 // This function allows verification when the certificate is provided separately 132 // from the signature, or when you want to verify against a different certificate 133 // than the one embedded in the signature. 134 // 135 // This is useful for scenarios where: 136 // - Signatures are detached and don't contain certificates 137 // - You want to verify against a known trusted certificate 138 // - The signature certificate needs to be validated against external sources 139 // - Multiple certificates might be valid for the same signature 140 // 141 // Parameters: 142 // - data: The original data that was signed 143 // - signature: The signature to verify (certificate will be temporarily replaced) 144 // - certificate: The specific certificate to use for verification 145 // - opts: Verification options controlling validation behavior 146 // 147 // Returns nil if the signature is valid with the provided certificate, 148 // or an error describing the validation failure. 149 // 150 // The function temporarily replaces the certificate in the signature object 151 // for verification, then restores the original certificate afterward. 152 // 153 // Example: 154 // 155 // // Verify signature against a known trusted certificate 156 // trustedCert, err := x509.ParseCertificate(knownCertDER) 157 // if err != nil { 158 // log.Fatal(err) 159 // } 160 // 161 // err = VerifyWithCertificate(data, signature, trustedCert, DefaultVerifyOptions()) 162 // if err != nil { 163 // log.Printf("Signature verification failed: %v", err) 164 // return 165 // } 166 // 167 // fmt.Println("Signature verified with trusted certificate") 168 func VerifyWithCertificate(data []byte, signature *Signature, certificate *x509.Certificate, opts VerifyOptions) error { 169 if signature == nil { 170 return fmt.Errorf("signature is nil") 171 } 172 173 if certificate == nil { 174 return ErrMissingCertificate 175 } 176 177 // Temporarily replace the certificate in the signature 178 originalCert := signature.Certificate 179 signature.Certificate = certificate 180 defer func() { 181 signature.Certificate = originalCert 182 }() 183 184 return VerifySignature(data, signature, opts) 185 } 186 187 // VerifyDetachedSignature verifies a detached signature. 188 // Detached signatures contain only the signature bytes without the original 189 // data or metadata. This function is useful for verifying raw signature bytes 190 // when you have the certificate and hash algorithm separately. 191 // 192 // A detached signature verification requires: 193 // - The original signed data 194 // - Raw signature bytes 195 // - The signer's certificate 196 // - The hash algorithm that was used during signing 197 // 198 // Parameters: 199 // - data: The original data that was signed 200 // - signatureData: Signature bytes in raw format (without PKCS#7 container) 201 // - certificate: The signer's certificate containing the public key 202 // - hashAlgo: The hash algorithm used during signing 203 // 204 // Returns nil if the detached signature is valid, or an error if verification fails. 205 // 206 // The function automatically detects the signature algorithm from the certificate's 207 // public key and creates a temporary Signature object for verification. 208 // 209 // Example: 210 // 211 // // Read signature from a .sig file 212 // sigBytes, err := os.ReadFile("document.pdf.sig") 213 // if err != nil { 214 // log.Fatal(err) 215 // } 216 // 217 // // Load signer certificate 218 // cert, err := loadCertificate("signer.crt") 219 // if err != nil { 220 // log.Fatal(err) 221 // } 222 // 223 // // Verify the detached signature 224 // err = VerifyDetachedSignature(documentData, sigBytes, cert, crypto.SHA256) 225 // if err != nil { 226 // log.Printf("Detached signature verification failed: %v", err) 227 // return 228 // } 229 // 230 // fmt.Println("Detached signature is valid") 231 func VerifyDetachedSignature(data []byte, signatureData []byte, certificate *x509.Certificate, hashAlgo crypto.Hash) error { 232 if certificate == nil { 233 return ErrMissingCertificate 234 } 235 236 // Determine the algorithm from the public key 237 algo, err := GetSignatureAlgorithm(certificate.PublicKey) 238 if err != nil { 239 return err 240 } 241 242 // For detached signatures, verify directly using algorithm-specific functions 243 // since signatureData contains raw signature bytes, not PKCS#7 data 244 switch algo { 245 case AlgorithmRSA: 246 // Compute digest for RSA verification 247 hasher := hashAlgo.New() 248 hasher.Write(data) 249 digest := hasher.Sum(nil) 250 return verifyRSASignature(certificate.PublicKey, digest, signatureData, hashAlgo) 251 252 case AlgorithmECDSA: 253 // Compute digest for ECDSA verification 254 hasher := hashAlgo.New() 255 hasher.Write(data) 256 digest := hasher.Sum(nil) 257 return verifyECDSASignature(certificate.PublicKey, digest, signatureData, hashAlgo) 258 259 case AlgorithmEd25519: 260 // Ed25519 verifies the message directly, not a hash 261 return verifyEd25519Signature(certificate.PublicKey, data, signatureData) 262 263 default: 264 return fmt.Errorf("unsupported algorithm for detached verification: %s", algo) 265 } 266 } 267 268 // verifyRSASignature verifies an RSA signature 269 func verifyRSASignature(publicKey crypto.PublicKey, digest, signature []byte, hashAlgo crypto.Hash) error { 270 rsaKey, ok := publicKey.(*rsa.PublicKey) 271 if !ok { 272 return fmt.Errorf("public key is not an RSA key") 273 } 274 275 err := rsa.VerifyPKCS1v15(rsaKey, hashAlgo, digest, signature) 276 if err != nil { 277 return ErrVerificationFailed 278 } 279 280 return nil 281 } 282 283 // verifyECDSASignature verifies an ECDSA signature 284 func verifyECDSASignature(publicKey crypto.PublicKey, digest, signature []byte, hashAlgo crypto.Hash) error { 285 ecdsaKey, ok := publicKey.(*ecdsa.PublicKey) 286 if !ok { 287 return fmt.Errorf("public key is not an ECDSA key") 288 } 289 290 // ECDSA signatures are typically DER-encoded 291 // For simplicity, we'll use ecdsa.VerifyASN1 292 if !ecdsa.VerifyASN1(ecdsaKey, digest, signature) { 293 return ErrVerificationFailed 294 } 295 296 return nil 297 } 298 299 // verifyEd25519Signature verifies an Ed25519 signature 300 func verifyEd25519Signature(publicKey crypto.PublicKey, message, signature []byte) error { 301 ed25519Key, ok := publicKey.(ed25519.PublicKey) 302 if !ok { 303 return fmt.Errorf("public key is not an Ed25519 key") 304 } 305 306 // Ed25519 verifies the message directly, not a hash 307 if !ed25519.Verify(ed25519Key, message, signature) { 308 return ErrVerificationFailed 309 } 310 311 return nil 312 } 313 314 // verifyCertificateChain verifies the certificate chain 315 func verifyCertificateChain(cert *x509.Certificate, chain []*x509.Certificate, opts VerifyOptions) error { 316 // Create verification options 317 verifyOpts := x509.VerifyOptions{ 318 Roots: opts.Roots, 319 Intermediates: opts.Intermediates, 320 CurrentTime: opts.VerifyTime, 321 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}, 322 } 323 324 // Add chain certificates to intermediates 325 if verifyOpts.Intermediates == nil && len(chain) > 0 { 326 verifyOpts.Intermediates = x509.NewCertPool() 327 for _, c := range chain { 328 verifyOpts.Intermediates.AddCert(c) 329 } 330 } 331 332 // Verify the certificate chain 333 _, err := cert.Verify(verifyOpts) 334 if err != nil { 335 return fmt.Errorf("chain verification failed: %w", err) 336 } 337 338 return nil 339 } 340 341 // VerifyTimestamp verifies a timestamp on a signature 342 func VerifyTimestamp(signature *Signature, opts VerifyOptions) error { 343 if signature.Timestamp == nil { 344 return fmt.Errorf("signature does not have a timestamp") 345 } 346 347 // Verify the timestamp certificate 348 if signature.Timestamp.Certificate != nil { 349 now := opts.VerifyTime 350 if now.IsZero() { 351 now = time.Now() 352 } 353 354 if now.Before(signature.Timestamp.Certificate.NotBefore) { 355 return fmt.Errorf("timestamp certificate is not yet valid") 356 } 357 358 if now.After(signature.Timestamp.Certificate.NotAfter) { 359 return fmt.Errorf("timestamp certificate has expired") 360 } 361 } 362 363 // In a full implementation, we would verify the RFC 3161 timestamp token 364 // For now, we just check that the timestamp exists 365 if len(signature.Timestamp.Token) == 0 { 366 return ErrInvalidTimestamp 367 } 368 369 return nil 370 } 371 372 // Utility functions for verification 373 374 // ExtractCertificateFromSignature extracts the signer's certificate from a signature. 375 // This utility function provides safe access to the certificate embedded in a 376 // signature, with proper error handling for missing certificates. 377 // 378 // Parameters: 379 // - signature: The signature containing the certificate to extract 380 // 381 // Returns the embedded X.509 certificate, or an error if the signature is nil 382 // or doesn't contain a certificate. 383 // 384 // This function is commonly used when you need to examine certificate properties 385 // or perform additional certificate validation outside of signature verification. 386 // 387 // Example: 388 // 389 // cert, err := ExtractCertificateFromSignature(signature) 390 // if err != nil { 391 // log.Printf("No certificate in signature: %v", err) 392 // return 393 // } 394 // 395 // fmt.Printf("Signer: %s\n", cert.Subject.CommonName) 396 // fmt.Printf("Issuer: %s\n", cert.Issuer.CommonName) 397 // fmt.Printf("Valid until: %s\n", cert.NotAfter.Format(time.RFC3339)) 398 func ExtractCertificateFromSignature(signature *Signature) (*x509.Certificate, error) { 399 if signature == nil { 400 return nil, fmt.Errorf("signature is nil") 401 } 402 403 if signature.Certificate == nil { 404 return nil, ErrMissingCertificate 405 } 406 407 return signature.Certificate, nil 408 } 409 410 // ExtractCertificateChainFromSignature extracts the certificate chain from a signature 411 func ExtractCertificateChainFromSignature(signature *Signature) ([]*x509.Certificate, error) { 412 if signature == nil { 413 return nil, fmt.Errorf("signature is nil") 414 } 415 416 if len(signature.CertificateChain) == 0 { 417 return nil, fmt.Errorf("signature does not contain a certificate chain") 418 } 419 420 return signature.CertificateChain, nil 421 } 422 423 // IsSignatureValid performs a quick structural validation of a signature. 424 // This function checks that the signature has the minimum required fields 425 // populated, but does not perform cryptographic verification. 426 // 427 // Validation checks: 428 // - Signature object is not nil 429 // - Signature data is not empty 430 // - Algorithm is specified 431 // - Hash algorithm is specified (not zero value) 432 // 433 // Parameters: 434 // - signature: The signature structure to validate 435 // 436 // Returns true if the signature structure appears valid, false otherwise. 437 // 438 // This is a lightweight check useful for early validation before attempting 439 // cryptographic verification. It helps catch obvious errors without the 440 // computational cost of actual signature verification. 441 // 442 // Example: 443 // 444 // if !IsSignatureValid(signature) { 445 // log.Printf("Signature structure is invalid") 446 // return 447 // } 448 // 449 // // Proceed with cryptographic verification 450 // err := VerifySignature(data, signature, opts) 451 func IsSignatureValid(signature *Signature) bool { 452 if signature == nil { 453 return false 454 } 455 456 if len(signature.Data) == 0 { 457 return false 458 } 459 460 if signature.Algorithm == "" { 461 return false 462 } 463 464 if signature.HashAlgorithm == 0 { 465 return false 466 } 467 468 return true 469 } 470 471 // GetSignatureInfo returns human-readable information about a signature. 472 // This function formats signature metadata into a readable string suitable 473 // for display, logging, or debugging purposes. 474 // 475 // The returned information includes: 476 // - Signature algorithm (RSA, ECDSA, Ed25519) 477 // - Hash algorithm (SHA256, SHA384, SHA512, etc.) 478 // - Signature format (PKCS#7, CMS, etc.) 479 // - Signer information from certificate (if available) 480 // - Certificate validity period 481 // - Timestamp information (if available) 482 // 483 // Parameters: 484 // - signature: The signature to describe 485 // 486 // Returns a multi-line string containing formatted signature information, 487 // or "No signature" if the signature is nil. 488 // 489 // This function is particularly useful for: 490 // - Logging signature details for audit trails 491 // - Debugging signature verification issues 492 // - Displaying signature properties to users 493 // - Generating signature reports 494 // 495 // Example: 496 // 497 // info := GetSignatureInfo(signature) 498 // fmt.Printf("Signature Details:\n%s", info) 499 // 500 // // Example output: 501 // // Algorithm: RSA 502 // // Hash: SHA256 503 // // Format: PKCS7 504 // // Signer: John Doe 505 // // Issuer: Corporate CA 506 // // Valid from: 2024-01-01T00:00:00Z 507 // // Valid until: 2025-01-01T00:00:00Z 508 func GetSignatureInfo(signature *Signature) string { 509 if signature == nil { 510 return "No signature" 511 } 512 513 info := fmt.Sprintf("Algorithm: %s\n", signature.Algorithm) 514 info += fmt.Sprintf("Hash: %s\n", HashAlgorithmToString(signature.HashAlgorithm)) 515 info += fmt.Sprintf("Format: %s\n", signature.Format) 516 517 if signature.Certificate != nil { 518 info += fmt.Sprintf("Signer: %s\n", signature.Certificate.Subject.CommonName) 519 info += fmt.Sprintf("Issuer: %s\n", signature.Certificate.Issuer.CommonName) 520 info += fmt.Sprintf("Valid from: %s\n", signature.Certificate.NotBefore.Format(time.RFC3339)) 521 info += fmt.Sprintf("Valid until: %s\n", signature.Certificate.NotAfter.Format(time.RFC3339)) 522 } 523 524 if signature.Timestamp != nil { 525 info += fmt.Sprintf("Timestamp: %s\n", signature.Timestamp.Time.Format(time.RFC3339)) 526 } 527 528 return info 529 } 530 531 // verifyPKCS7SignatureFormat verifies a PKCS#7 format signature using Smallstep PKCS#7 library 532 func verifyPKCS7SignatureFormat(data []byte, signature *Signature, opts VerifyOptions) error { 533 // Parse the PKCS#7 signature data 534 p7, err := pkcs7.Parse(signature.Data) 535 if err != nil { 536 return fmt.Errorf("failed to parse PKCS#7 signature: %w", err) 537 } 538 539 // CRITICAL SECURITY FIX: Always set the content to the provided data 540 // This ensures we verify against the actual data being tested, not embedded content 541 if signature.Format == FormatPKCS7Detached { 542 // For detached signatures, set the content 543 p7.Content = data 544 } else { 545 // For attached signatures, we need to verify that the embedded content 546 // matches the provided data to prevent signature substitution attacks 547 if len(p7.Content) != len(data) { 548 return fmt.Errorf("data length mismatch: provided %d bytes, signature contains %d bytes", len(data), len(p7.Content)) 549 } 550 for i := range data { 551 if p7.Content[i] != data[i] { 552 return fmt.Errorf("data content mismatch: provided data does not match signed content") 553 } 554 } 555 // Set content to ensure verification uses the provided data 556 p7.Content = data 557 } 558 559 // CRITICAL SECURITY FIX: Verify against the specific certificate 560 // The p7.Verify() call alone doesn't verify the signature was created by the expected certificate 561 if signature.Certificate != nil { 562 // First do standard PKCS#7 verification 563 err = p7.Verify() 564 if err != nil { 565 return fmt.Errorf("PKCS#7 signature verification failed: %w", err) 566 } 567 568 // Then verify the signature was created by the expected certificate 569 // Check if the expected certificate is in the PKCS#7 signers 570 signerCert := p7.GetOnlySigner() 571 if signerCert == nil { 572 return fmt.Errorf("PKCS#7 signature does not contain exactly one signer") 573 } 574 575 // Compare the certificates by their raw bytes (most reliable method) 576 if !signerCert.Equal(signature.Certificate) { 577 return fmt.Errorf("signature was not created by the expected certificate") 578 } 579 } else { 580 // Standard PKCS#7 verification when no specific certificate is required 581 err = p7.Verify() 582 if err != nil { 583 return fmt.Errorf("PKCS#7 signature verification failed: %w", err) 584 } 585 } 586 587 return nil 588 } 589 590 // verifyEd25519PKCS7Signature verifies an Ed25519 PKCS#7 signature using RFC 8419 ASN.1 implementation 591 func verifyEd25519PKCS7Signature(data []byte, signature *Signature) error { 592 // Use RFC 8419 Ed25519 PKCS#7 verification 593 info, err := internalcrypto.VerifyEd25519PKCS7Signature(data, signature.Data) 594 if err != nil { 595 return fmt.Errorf("Ed25519 PKCS#7 verification failed: %w", err) 596 } 597 598 if !info.Verified { 599 return ErrVerificationFailed 600 } 601 602 // Verify the certificate matches (if provided in signature) 603 if signature.Certificate != nil { 604 if !signature.Certificate.Equal(info.Certificate) { 605 return fmt.Errorf("certificate mismatch between signature and PKCS#7 data") 606 } 607 } else { 608 // Populate certificate from PKCS#7 data 609 signature.Certificate = info.Certificate 610 } 611 612 return nil 613 }