| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package pkcs7 |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "crypto/hmac" |
| 22 | "crypto/rsa" |
| 23 | "crypto/x509" |
| 24 | "encoding/asn1" |
| 25 | "errors" |
| 26 | "fmt" |
| 27 | "math/big" |
| 28 | "time" |
| 29 | |
| 30 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 31 | "github.com/sassoftware/relic/v7/signers/sigerrors" |
| 32 | ) |
| 33 | |
| 34 | type Signature struct { |
| 35 | SignerInfo *SignerInfo |
| 36 | Certificate *x509.Certificate |
| 37 | Intermediates []*x509.Certificate |
| 38 | CertError error |
| 39 | } |
| 40 | |
| 41 | // Verify the content in a SignedData structure. External content may be |
| 42 | // provided if it is a detached signature. Information about the signature is |
| 43 | // returned, however X509 chains are not validated. Call VerifyChain() to |
| 44 | // complete the verification process. |
| 45 | // |
| 46 | // If skipDigests is true, then the main content section is not checked, but |
| 47 | // the SignerInfos are still checked for a valid signature. |
| 48 | func (sd *SignedData) Verify(externalContent []byte, skipDigests bool) (Signature, error) { |
| 49 | var content []byte |
| 50 | if !skipDigests { |
| 51 | var err error |
| 52 | content, err = sd.ContentInfo.Bytes() |
| 53 | if err != nil { |
| 54 | return Signature{}, err |
| 55 | } else if content == nil { |
| 56 | if externalContent == nil { |
| 57 | return Signature{}, errors.New("pkcs7: missing content") |
| 58 | } |
| 59 | content = externalContent |
| 60 | } else if externalContent != nil { |
| 61 | if !bytes.Equal(externalContent, content) { |
| 62 | return Signature{}, errors.New("pkcs7: internal and external content were both provided but are not equal") |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | if len(sd.SignerInfos) == 0 { |
| 67 | return Signature{}, sigerrors.NotSignedError{Type: "pkcs7"} |
| 68 | } |
| 69 | certs, certErr := sd.Certificates.Parse() |
| 70 | // postpone handling of cert parse error until something is actually missing |
| 71 | var cert *x509.Certificate |
| 72 | var sig Signature |
| 73 | for _, si := range sd.SignerInfos { |
| 74 | var err error |
| 75 | cert, err = si.Verify(content, skipDigests, certs) |
| 76 | if err != nil { |
| 77 | if errors.As(err, &MissingCertificateError{}) && certErr != nil { |
| 78 | // now surface the parse error |
| 79 | err = certErr |
| 80 | } |
| 81 | return Signature{}, err |
| 82 | } |
| 83 | sig = Signature{ |
| 84 | SignerInfo: &si, |
| 85 | Certificate: cert, |
| 86 | Intermediates: certs, |
| 87 | CertError: certErr, |
| 88 | } |
| 89 | } |
| 90 | return sig, nil |
| 91 | } |
| 92 | |
| 93 | // Find the certificate that signed this SignerInfo from the bucket of certs |
| 94 | func (si *SignerInfo) FindCertificate(certs []*x509.Certificate) (*x509.Certificate, error) { |
| 95 | is := si.IssuerAndSerialNumber |
| 96 | for _, cert := range certs { |
| 97 | if bytes.Equal(cert.RawIssuer, is.IssuerName.FullBytes) && cert.SerialNumber.Cmp(is.SerialNumber) == 0 { |
| 98 | return cert, nil |
| 99 | } |
| 100 | } |
| 101 | return nil, MissingCertificateError{Issuer: is.IssuerName, SerialNumber: is.SerialNumber} |
| 102 | } |
| 103 | |
| 104 | type MissingCertificateError struct { |
| 105 | Issuer asn1.RawValue |
| 106 | SerialNumber *big.Int |
| 107 | } |
| 108 | |
| 109 | func (e MissingCertificateError) Error() string { |
| 110 | name := x509tools.FormatPkixName(e.Issuer.FullBytes, x509tools.NameStyleLdap) |
| 111 | return fmt.Sprintf("certificate missing from signedData: serial=%x issuer: %s", e.SerialNumber, name) |
| 112 | } |
| 113 | |
| 114 | // Verify the signature contained in this SignerInfo and return the leaf |
| 115 | // certificate. X509 chains are not validated. |
| 116 | func (si *SignerInfo) Verify(content []byte, skipDigests bool, certs []*x509.Certificate) (*x509.Certificate, error) { |
| 117 | hash, err := x509tools.PkixDigestToHashE(si.DigestAlgorithm) |
| 118 | if err != nil { |
| 119 | return nil, fmt.Errorf("pkcs7: %w", err) |
| 120 | } |
| 121 | var digest []byte |
| 122 | if !skipDigests { |
| 123 | w := hash.New() |
| 124 | w.Write(content) |
| 125 | digest = w.Sum(nil) |
| 126 | } |
| 127 | if len(si.AuthenticatedAttributes) != 0 { |
| 128 | // check the content digest against the messageDigest attribute |
| 129 | var md []byte |
| 130 | if err := si.AuthenticatedAttributes.GetOne(OidAttributeMessageDigest, &md); err != nil { |
| 131 | return nil, err |
| 132 | } else if digest != nil && !hmac.Equal(md, digest) { |
| 133 | return nil, errors.New("pkcs7: content digest does not match") |
| 134 | } |
| 135 | // now pivot to verifying the hash over the authenticated attributes |
| 136 | w := hash.New() |
| 137 | attrbytes, err := si.AuthenticatedAttributesBytes() |
| 138 | if err != nil { |
| 139 | return nil, fmt.Errorf("verifying authenticated attributes: %w", err) |
| 140 | } |
| 141 | w.Write(attrbytes) |
| 142 | digest = w.Sum(nil) |
| 143 | } // otherwise the content hash is verified directly |
| 144 | cert, err := si.FindCertificate(certs) |
| 145 | if err != nil { |
| 146 | return nil, err |
| 147 | } |
| 148 | // If skipDigests is set and AuthenticatedAttributes is not present then |
| 149 | // there's no digest to check the signature against. For RSA at least it's |
| 150 | // possible to decrypt the signature and check the padding but there's not |
| 151 | // much point to it. |
| 152 | if digest != nil { |
| 153 | err = x509tools.PkixVerify(cert.PublicKey, si.DigestAlgorithm, si.DigestEncryptionAlgorithm, digest, si.EncryptedDigest) |
| 154 | if err == rsa.ErrVerification { |
| 155 | // "Symantec Time Stamping Services Signer" seems to be emitting |
| 156 | // signatures without the AlgorithmIdentifier strucuture, so try |
| 157 | // without it. |
| 158 | err = x509tools.Verify(cert.PublicKey, 0, digest, si.EncryptedDigest) |
| 159 | } |
| 160 | } |
| 161 | return cert, err |
| 162 | } |
| 163 | |
| 164 | // Verify the X509 chain from a signature against the given roots. extraCerts |
| 165 | // will be added to the intermediates if provided. usage gives the certificate |
| 166 | // usage required for the leaf certificate, or ExtKeyUsageAny otherwise. If a |
| 167 | // PKCS#9 trusted timestamp was found, pass that timestamp in currentTime to |
| 168 | // validate the chain as of the time of the signature. |
| 169 | func (info Signature) VerifyChain(roots *x509.CertPool, extraCerts []*x509.Certificate, usage x509.ExtKeyUsage, currentTime time.Time) error { |
| 170 | pool := x509.NewCertPool() |
| 171 | for _, cert := range extraCerts { |
| 172 | pool.AddCert(cert) |
| 173 | } |
| 174 | for _, cert := range info.Intermediates { |
| 175 | pool.AddCert(cert) |
| 176 | } |
| 177 | opts := x509.VerifyOptions{ |
| 178 | Intermediates: pool, |
| 179 | Roots: roots, |
| 180 | CurrentTime: currentTime, |
| 181 | KeyUsages: []x509.ExtKeyUsage{usage}, |
| 182 | } |
| 183 | _, err := info.Certificate.Verify(opts) |
| 184 | if err == nil { |
| 185 | return nil |
| 186 | } |
| 187 | if e := new(x509.UnknownAuthorityError); errors.As(err, e) && info.CertError != nil { |
| 188 | // surface a saved cert parse error |
| 189 | return fmt.Errorf("%w: after failing to parse a bundled certificate: %s", err, info.CertError) |
| 190 | } |
| 191 | return err |
| 192 | } |