| 1 | package pkcs7 |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto" |
| 6 | "crypto/subtle" |
| 7 | "crypto/x509" |
| 8 | "crypto/x509/pkix" |
| 9 | "encoding/asn1" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | // Verify is a wrapper around VerifyWithChain() that initializes an empty |
| 16 | // trust store, effectively disabling certificate verification when validating |
| 17 | // a signature. |
| 18 | func (p7 *PKCS7) Verify() (err error) { |
| 19 | return p7.VerifyWithChain(nil) |
| 20 | } |
| 21 | |
| 22 | // VerifyWithChain checks the signatures of a PKCS7 object. |
| 23 | // |
| 24 | // If truststore is not nil, it also verifies the chain of trust of |
| 25 | // the end-entity signer cert to one of the roots in the |
| 26 | // truststore. When the PKCS7 object includes the signing time |
| 27 | // authenticated attr verifies the chain at that time and UTC now |
| 28 | // otherwise. |
| 29 | func (p7 *PKCS7) VerifyWithChain(truststore *x509.CertPool) (err error) { |
| 30 | if len(p7.Signers) == 0 { |
| 31 | return errors.New("pkcs7: Message has no signers") |
| 32 | } |
| 33 | for _, signer := range p7.Signers { |
| 34 | if err := verifySignature(p7, signer, truststore); err != nil { |
| 35 | return err |
| 36 | } |
| 37 | } |
| 38 | return nil |
| 39 | } |
| 40 | |
| 41 | // VerifyWithChainAtTime checks the signatures of a PKCS7 object. |
| 42 | // |
| 43 | // If truststore is not nil, it also verifies the chain of trust of |
| 44 | // the end-entity signer cert to a root in the truststore at |
| 45 | // currentTime. It does not use the signing time authenticated |
| 46 | // attribute. |
| 47 | func (p7 *PKCS7) VerifyWithChainAtTime(truststore *x509.CertPool, currentTime time.Time) (err error) { |
| 48 | if len(p7.Signers) == 0 { |
| 49 | return errors.New("pkcs7: Message has no signers") |
| 50 | } |
| 51 | for _, signer := range p7.Signers { |
| 52 | if err := verifySignatureAtTime(p7, signer, truststore, currentTime); err != nil { |
| 53 | return err |
| 54 | } |
| 55 | } |
| 56 | return nil |
| 57 | } |
| 58 | |
| 59 | // SigningTimeNotValidError is returned when the signing time attribute |
| 60 | // falls outside of the signer certificate validity. |
| 61 | type SigningTimeNotValidError struct { |
| 62 | SigningTime time.Time |
| 63 | NotBefore time.Time // NotBefore of signer |
| 64 | NotAfter time.Time // NotAfter of signer |
| 65 | } |
| 66 | |
| 67 | func (e *SigningTimeNotValidError) Error() string { |
| 68 | return fmt.Sprintf("pkcs7: signing time %q is outside of certificate validity %q to %q", |
| 69 | e.SigningTime.Format(time.RFC3339), |
| 70 | e.NotBefore.Format(time.RFC3339), |
| 71 | e.NotAfter.Format(time.RFC3339)) |
| 72 | } |
| 73 | |
| 74 | func verifySignatureAtTime(p7 *PKCS7, signer signerInfo, truststore *x509.CertPool, currentTime time.Time) (err error) { |
| 75 | signedData := p7.Content |
| 76 | ee := getCertFromCertsByIssuerAndSerial(p7.Certificates, signer.IssuerAndSerialNumber) |
| 77 | if ee == nil { |
| 78 | return errors.New("pkcs7: No certificate for signer") |
| 79 | } |
| 80 | if len(signer.AuthenticatedAttributes) > 0 { |
| 81 | // TODO(fullsailor): First check the content type match |
| 82 | var ( |
| 83 | digest []byte |
| 84 | signingTime time.Time |
| 85 | ) |
| 86 | err := unmarshalAttribute(signer.AuthenticatedAttributes, OIDAttributeMessageDigest, &digest) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | hash, err := getHashForOID(signer.DigestAlgorithm.Algorithm) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | computed, err := calculateHash(p7.Hasher, hash, p7.Content) |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 | if subtle.ConstantTimeCompare(digest, computed) != 1 { |
| 99 | return &MessageDigestMismatchError{ |
| 100 | ExpectedDigest: digest, |
| 101 | ActualDigest: computed, |
| 102 | } |
| 103 | } |
| 104 | signedData, err = marshalAttributes(signer.AuthenticatedAttributes) |
| 105 | if err != nil { |
| 106 | return err |
| 107 | } |
| 108 | err = unmarshalAttribute(signer.AuthenticatedAttributes, OIDAttributeSigningTime, &signingTime) |
| 109 | if err == nil { |
| 110 | // signing time found, performing validity check |
| 111 | if signingTime.After(ee.NotAfter) || signingTime.Before(ee.NotBefore) { |
| 112 | return &SigningTimeNotValidError{ |
| 113 | SigningTime: signingTime, |
| 114 | NotBefore: ee.NotBefore, |
| 115 | NotAfter: ee.NotAfter, |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | if truststore != nil { |
| 121 | _, err = verifyCertChain(ee, p7.Certificates, truststore, currentTime) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | } |
| 126 | sigalg, err := getSignatureAlgorithm(signer.DigestEncryptionAlgorithm, signer.DigestAlgorithm) |
| 127 | if err != nil { |
| 128 | return err |
| 129 | } |
| 130 | return ee.CheckSignature(sigalg, signedData, signer.EncryptedDigest) |
| 131 | } |
| 132 | |
| 133 | func verifySignature(p7 *PKCS7, signer signerInfo, truststore *x509.CertPool) (err error) { |
| 134 | signedData := p7.Content |
| 135 | ee := getCertFromCertsByIssuerAndSerial(p7.Certificates, signer.IssuerAndSerialNumber) |
| 136 | if ee == nil { |
| 137 | return errors.New("pkcs7: No certificate for signer") |
| 138 | } |
| 139 | signingTime := time.Now().UTC() |
| 140 | if len(signer.AuthenticatedAttributes) > 0 { |
| 141 | // TODO(fullsailor): First check the content type match |
| 142 | var digest []byte |
| 143 | err := unmarshalAttribute(signer.AuthenticatedAttributes, OIDAttributeMessageDigest, &digest) |
| 144 | if err != nil { |
| 145 | return err |
| 146 | } |
| 147 | hash, err := getHashForOID(signer.DigestAlgorithm.Algorithm) |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | computed, err := calculateHash(p7.Hasher, hash, p7.Content) |
| 152 | if err != nil { |
| 153 | return err |
| 154 | } |
| 155 | if subtle.ConstantTimeCompare(digest, computed) != 1 { |
| 156 | return &MessageDigestMismatchError{ |
| 157 | ExpectedDigest: digest, |
| 158 | ActualDigest: computed, |
| 159 | } |
| 160 | } |
| 161 | signedData, err = marshalAttributes(signer.AuthenticatedAttributes) |
| 162 | if err != nil { |
| 163 | return err |
| 164 | } |
| 165 | err = unmarshalAttribute(signer.AuthenticatedAttributes, OIDAttributeSigningTime, &signingTime) |
| 166 | if err == nil { |
| 167 | // signing time found, performing validity check |
| 168 | if signingTime.After(ee.NotAfter) || signingTime.Before(ee.NotBefore) { |
| 169 | return &SigningTimeNotValidError{ |
| 170 | SigningTime: signingTime, |
| 171 | NotBefore: ee.NotBefore, |
| 172 | NotAfter: ee.NotAfter, |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | if truststore != nil { |
| 178 | _, err = verifyCertChain(ee, p7.Certificates, truststore, signingTime) |
| 179 | if err != nil { |
| 180 | return err |
| 181 | } |
| 182 | } |
| 183 | sigalg, err := getSignatureAlgorithm(signer.DigestEncryptionAlgorithm, signer.DigestAlgorithm) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | return ee.CheckSignature(sigalg, signedData, signer.EncryptedDigest) |
| 188 | } |
| 189 | |
| 190 | // GetOnlySigner returns an x509.Certificate for the first signer of the signed |
| 191 | // data payload. If there are more or less than one signer, nil is returned |
| 192 | func (p7 *PKCS7) GetOnlySigner() *x509.Certificate { |
| 193 | if len(p7.Signers) != 1 { |
| 194 | return nil |
| 195 | } |
| 196 | signer := p7.Signers[0] |
| 197 | return getCertFromCertsByIssuerAndSerial(p7.Certificates, signer.IssuerAndSerialNumber) |
| 198 | } |
| 199 | |
| 200 | // UnmarshalSignedAttribute decodes a single attribute from the signer info |
| 201 | func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error { |
| 202 | sd, ok := p7.raw.(signedData) |
| 203 | if !ok { |
| 204 | return errors.New("pkcs7: payload is not signedData content") |
| 205 | } |
| 206 | if len(sd.SignerInfos) < 1 { |
| 207 | return errors.New("pkcs7: payload has no signers") |
| 208 | } |
| 209 | attributes := sd.SignerInfos[0].AuthenticatedAttributes |
| 210 | return unmarshalAttribute(attributes, attributeType, out) |
| 211 | } |
| 212 | |
| 213 | func parseSignedData(data []byte) (*PKCS7, error) { |
| 214 | var sd signedData |
| 215 | asn1.Unmarshal(data, &sd) |
| 216 | certs, err := sd.Certificates.Parse() |
| 217 | if err != nil { |
| 218 | return nil, err |
| 219 | } |
| 220 | // fmt.Printf("--> Signed Data Version %d\n", sd.Version) |
| 221 | |
| 222 | var compound asn1.RawValue |
| 223 | var content unsignedData |
| 224 | |
| 225 | // The Content.Bytes maybe empty on PKI responses. |
| 226 | if len(sd.ContentInfo.Content.Bytes) > 0 { |
| 227 | if _, err := asn1.Unmarshal(sd.ContentInfo.Content.Bytes, &compound); err != nil { |
| 228 | return nil, err |
| 229 | } |
| 230 | } |
| 231 | // Compound octet string |
| 232 | if compound.IsCompound { |
| 233 | if compound.Tag == 4 { |
| 234 | for len(compound.Bytes) > 0 { |
| 235 | var cdata asn1.RawValue |
| 236 | if _, err = asn1.Unmarshal(compound.Bytes, &cdata); err != nil { |
| 237 | return nil, err |
| 238 | } |
| 239 | content = append(content, cdata.Bytes...) |
| 240 | compound.Bytes = compound.Bytes[len(cdata.FullBytes):] |
| 241 | } |
| 242 | } else { |
| 243 | content = compound.Bytes |
| 244 | } |
| 245 | } else { |
| 246 | // assuming this is tag 04 |
| 247 | content = compound.Bytes |
| 248 | } |
| 249 | return &PKCS7{ |
| 250 | Content: content, |
| 251 | Certificates: certs, |
| 252 | CRLs: sd.CRLs, |
| 253 | Signers: sd.SignerInfos, |
| 254 | raw: sd}, nil |
| 255 | } |
| 256 | |
| 257 | // verifyCertChain takes an end-entity certs, a list of potential intermediates and a |
| 258 | // truststore, and built all potential chains between the EE and a trusted root. |
| 259 | // |
| 260 | // When verifying chains that may have expired, currentTime can be set to a past date |
| 261 | // to allow the verification to pass. If unset, currentTime is set to the current UTC time. |
| 262 | func verifyCertChain(ee *x509.Certificate, certs []*x509.Certificate, truststore *x509.CertPool, currentTime time.Time) (chains [][]*x509.Certificate, err error) { |
| 263 | intermediates := x509.NewCertPool() |
| 264 | for _, intermediate := range certs { |
| 265 | intermediates.AddCert(intermediate) |
| 266 | } |
| 267 | verifyOptions := x509.VerifyOptions{ |
| 268 | Roots: truststore, |
| 269 | Intermediates: intermediates, |
| 270 | KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}, |
| 271 | CurrentTime: currentTime, |
| 272 | } |
| 273 | chains, err = ee.Verify(verifyOptions) |
| 274 | if err != nil { |
| 275 | return chains, fmt.Errorf("pkcs7: failed to verify certificate chain: %v", err) |
| 276 | } |
| 277 | return |
| 278 | } |
| 279 | |
| 280 | // MessageDigestMismatchError is returned when the signer data digest does not |
| 281 | // match the computed digest for the contained content |
| 282 | type MessageDigestMismatchError struct { |
| 283 | ExpectedDigest []byte |
| 284 | ActualDigest []byte |
| 285 | } |
| 286 | |
| 287 | func (err *MessageDigestMismatchError) Error() string { |
| 288 | return fmt.Sprintf("pkcs7: Message digest mismatch\n\tExpected: %X\n\tActual : %X", err.ExpectedDigest, err.ActualDigest) |
| 289 | } |
| 290 | |
| 291 | func getSignatureAlgorithm(digestEncryption, digest pkix.AlgorithmIdentifier) (x509.SignatureAlgorithm, error) { |
| 292 | switch { |
| 293 | case digestEncryption.Algorithm.Equal(OIDDigestAlgorithmECDSASHA1): |
| 294 | return x509.ECDSAWithSHA1, nil |
| 295 | case digestEncryption.Algorithm.Equal(OIDDigestAlgorithmECDSASHA256): |
| 296 | return x509.ECDSAWithSHA256, nil |
| 297 | case digestEncryption.Algorithm.Equal(OIDDigestAlgorithmECDSASHA384): |
| 298 | return x509.ECDSAWithSHA384, nil |
| 299 | case digestEncryption.Algorithm.Equal(OIDDigestAlgorithmECDSASHA512): |
| 300 | return x509.ECDSAWithSHA512, nil |
| 301 | case digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmRSA), |
| 302 | digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA1), |
| 303 | digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA256), |
| 304 | digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA384), |
| 305 | digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA512): |
| 306 | switch { |
| 307 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA1), digest.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA1): |
| 308 | return x509.SHA1WithRSA, nil |
| 309 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA256), digest.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA256): |
| 310 | return x509.SHA256WithRSA, nil |
| 311 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA384), digest.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA384): |
| 312 | return x509.SHA384WithRSA, nil |
| 313 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA512), digest.Algorithm.Equal(OIDEncryptionAlgorithmRSASHA512): |
| 314 | return x509.SHA512WithRSA, nil |
| 315 | default: |
| 316 | return -1, fmt.Errorf("pkcs7: unsupported digest %q for encryption algorithm %q", |
| 317 | digest.Algorithm.String(), digestEncryption.Algorithm.String()) |
| 318 | } |
| 319 | case digestEncryption.Algorithm.Equal(OIDDigestAlgorithmDSA), |
| 320 | digestEncryption.Algorithm.Equal(OIDDigestAlgorithmDSASHA1): |
| 321 | switch { |
| 322 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA1): |
| 323 | return x509.DSAWithSHA1, nil |
| 324 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA256): |
| 325 | return x509.DSAWithSHA256, nil |
| 326 | default: |
| 327 | return -1, fmt.Errorf("pkcs7: unsupported digest %q for encryption algorithm %q", |
| 328 | digest.Algorithm.String(), digestEncryption.Algorithm.String()) |
| 329 | } |
| 330 | case digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmECDSAP256), |
| 331 | digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmECDSAP384), |
| 332 | digestEncryption.Algorithm.Equal(OIDEncryptionAlgorithmECDSAP521): |
| 333 | switch { |
| 334 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA1): |
| 335 | return x509.ECDSAWithSHA1, nil |
| 336 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA256): |
| 337 | return x509.ECDSAWithSHA256, nil |
| 338 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA384): |
| 339 | return x509.ECDSAWithSHA384, nil |
| 340 | case digest.Algorithm.Equal(OIDDigestAlgorithmSHA512): |
| 341 | return x509.ECDSAWithSHA512, nil |
| 342 | default: |
| 343 | return -1, fmt.Errorf("pkcs7: unsupported digest %q for encryption algorithm %q", |
| 344 | digest.Algorithm.String(), digestEncryption.Algorithm.String()) |
| 345 | } |
| 346 | default: |
| 347 | return -1, fmt.Errorf("pkcs7: unsupported algorithm %q", |
| 348 | digestEncryption.Algorithm.String()) |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | func getCertFromCertsByIssuerAndSerial(certs []*x509.Certificate, ias issuerAndSerial) *x509.Certificate { |
| 353 | for _, cert := range certs { |
| 354 | if isCertMatchForIssuerAndSerial(cert, ias) { |
| 355 | return cert |
| 356 | } |
| 357 | } |
| 358 | return nil |
| 359 | } |
| 360 | |
| 361 | func unmarshalAttribute(attrs []attribute, attributeType asn1.ObjectIdentifier, out interface{}) error { |
| 362 | for _, attr := range attrs { |
| 363 | if attr.Type.Equal(attributeType) { |
| 364 | _, err := asn1.Unmarshal(attr.Value.Bytes, out) |
| 365 | return err |
| 366 | } |
| 367 | } |
| 368 | return errors.New("pkcs7: attribute type not in attributes") |
| 369 | } |
| 370 | |
| 371 | func calculateHash(hasher Hasher, hashFunc crypto.Hash, content []byte) (computed []byte, err error) { |
| 372 | if hasher != nil { |
| 373 | computed, err = hasher.Hash(hashFunc, bytes.NewReader(content)) |
| 374 | } else { |
| 375 | if !hashFunc.Available() { |
| 376 | return nil, fmt.Errorf("hash function %v not available", hashFunc) |
| 377 | } |
| 378 | |
| 379 | h := hashFunc.New() |
| 380 | _, _ = h.Write(content) |
| 381 | computed = h.Sum(nil) |
| 382 | } |
| 383 | |
| 384 | return |
| 385 | } |