| 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 pkcs9 |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "context" |
| 22 | "crypto" |
| 23 | "crypto/x509" |
| 24 | "errors" |
| 25 | "fmt" |
| 26 | "time" |
| 27 | |
| 28 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 29 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 30 | ) |
| 31 | |
| 32 | func TimestampAndMarshal(ctx context.Context, psd *pkcs7.ContentInfoSignedData, timestamper Timestamper, authenticode bool) (*TimestampedSignature, error) { |
| 33 | if timestamper != nil { |
| 34 | signerInfo := &psd.Content.SignerInfos[0] |
| 35 | hash, err := x509tools.PkixDigestToHashE(signerInfo.DigestAlgorithm) |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | token, err := timestamper.Timestamp(ctx, &Request{EncryptedDigest: signerInfo.EncryptedDigest, Hash: hash}) |
| 40 | if err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | if authenticode { |
| 44 | err = AddStampToSignedAuthenticode(signerInfo, *token) |
| 45 | } else { |
| 46 | err = AddStampToSignedData(signerInfo, *token) |
| 47 | } |
| 48 | if err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | } |
| 52 | verified, err := psd.Content.Verify(nil, false) |
| 53 | if err != nil { |
| 54 | return nil, fmt.Errorf("pkcs7: failed signature self-check: %w", err) |
| 55 | } |
| 56 | ts, err := VerifyOptionalTimestamp(verified) |
| 57 | if err != nil { |
| 58 | return nil, fmt.Errorf("pkcs7: failed signature self-check: %w", err) |
| 59 | } |
| 60 | blob, err := psd.Marshal() |
| 61 | if err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | ts.Raw = blob |
| 65 | return &ts, err |
| 66 | } |
| 67 | |
| 68 | // Attach a RFC 3161 timestamp to a PKCS#7 SignerInfo |
| 69 | func AddStampToSignedData(signerInfo *pkcs7.SignerInfo, token pkcs7.ContentInfoSignedData) error { |
| 70 | return signerInfo.UnauthenticatedAttributes.Add(OidAttributeTimeStampToken, token) |
| 71 | } |
| 72 | |
| 73 | // Attach a RFC 3161 timestamp to a PKCS#7 SignerInfo using the OID for authenticode signatures |
| 74 | func AddStampToSignedAuthenticode(signerInfo *pkcs7.SignerInfo, token pkcs7.ContentInfoSignedData) error { |
| 75 | return signerInfo.UnauthenticatedAttributes.Add(OidSpcTimeStampToken, token) |
| 76 | } |
| 77 | |
| 78 | // Validated timestamp token |
| 79 | type CounterSignature struct { |
| 80 | pkcs7.Signature |
| 81 | Hash crypto.Hash |
| 82 | SigningTime time.Time |
| 83 | } |
| 84 | |
| 85 | // Validated signature containing a optional timestamp token |
| 86 | type TimestampedSignature struct { |
| 87 | pkcs7.Signature |
| 88 | CounterSignature *CounterSignature |
| 89 | Raw []byte |
| 90 | } |
| 91 | |
| 92 | // Look for a timestamp (counter-signature or timestamp token) in the |
| 93 | // UnauthenticatedAttributes of the given already-validated signature and check |
| 94 | // its integrity. The certificate chain is not checked; call VerifyChain() on |
| 95 | // the result to validate it fully. Returns nil if no timestamp is present. |
| 96 | func VerifyPkcs7(sig pkcs7.Signature) (*CounterSignature, error) { |
| 97 | var tst pkcs7.ContentInfoSignedData |
| 98 | // check several OIDs for timestamp tokens |
| 99 | err := sig.SignerInfo.UnauthenticatedAttributes.GetOne(OidAttributeTimeStampToken, &tst) |
| 100 | if _, ok := err.(pkcs7.ErrNoAttribute); ok { |
| 101 | err = sig.SignerInfo.UnauthenticatedAttributes.GetOne(OidSpcTimeStampToken, &tst) |
| 102 | } |
| 103 | var imprintHash crypto.Hash |
| 104 | if err == nil { |
| 105 | // timestamptoken is a fully nested signedData containing a TSTInfo |
| 106 | // that digests the parent signature blob |
| 107 | return Verify(&tst, sig.SignerInfo.EncryptedDigest, sig.Intermediates) |
| 108 | } else if _, ok := err.(pkcs7.ErrNoAttribute); ok { |
| 109 | tsi := new(pkcs7.SignerInfo) |
| 110 | if err := sig.SignerInfo.UnauthenticatedAttributes.GetOne(OidAttributeCounterSign, tsi); err != nil { |
| 111 | if _, ok := err.(pkcs7.ErrNoAttribute); ok { |
| 112 | return nil, nil |
| 113 | } |
| 114 | return nil, err |
| 115 | } |
| 116 | // counterSignature is simply a signerinfo. The certificate chain is |
| 117 | // included in the parent structure, and the timestamp signs the |
| 118 | // signature blob from the parent signerinfo |
| 119 | imprintHash, _ = x509tools.PkixDigestToHash(sig.SignerInfo.DigestAlgorithm) |
| 120 | return finishVerify(tsi, sig.SignerInfo.EncryptedDigest, sig.Intermediates, imprintHash, tsi, nil) |
| 121 | } |
| 122 | return nil, err |
| 123 | } |
| 124 | |
| 125 | // Look for a timestamp token or counter-signature in the given signature and |
| 126 | // return a structure that can be used to validate the signature's certificate |
| 127 | // chain. If no timestamp is present, then the current time will be used when |
| 128 | // validating the chain. |
| 129 | func VerifyOptionalTimestamp(sig pkcs7.Signature) (TimestampedSignature, error) { |
| 130 | tsig := TimestampedSignature{Signature: sig} |
| 131 | ts, err := VerifyPkcs7(sig) |
| 132 | if err != nil { |
| 133 | return tsig, err |
| 134 | } |
| 135 | tsig.CounterSignature = ts |
| 136 | return tsig, nil |
| 137 | } |
| 138 | |
| 139 | // Verify that the timestamp token has a valid certificate chain |
| 140 | func (cs CounterSignature) VerifyChain(roots *x509.CertPool, extraCerts []*x509.Certificate) error { |
| 141 | return cs.Signature.VerifyChain(roots, extraCerts, x509.ExtKeyUsageTimeStamping, cs.SigningTime) |
| 142 | } |
| 143 | |
| 144 | // Verify the certificate chain of a PKCS#7 signature. If the signature has a |
| 145 | // valid timestamp token attached, then the timestamp is used for validating |
| 146 | // the primary signature's chain, making the signature valid after the |
| 147 | // certificates have expired. |
| 148 | func (sig TimestampedSignature) VerifyChain(roots *x509.CertPool, extraCerts []*x509.Certificate, usage x509.ExtKeyUsage) error { |
| 149 | var signingTime time.Time |
| 150 | if sig.CounterSignature != nil { |
| 151 | if err := sig.CounterSignature.VerifyChain(roots, extraCerts); err != nil { |
| 152 | return fmt.Errorf("validating timestamp: %w", err) |
| 153 | } |
| 154 | signingTime = sig.CounterSignature.SigningTime |
| 155 | } |
| 156 | return sig.Signature.VerifyChain(roots, extraCerts, usage, signingTime) |
| 157 | } |
| 158 | |
| 159 | // Verify a non-RFC-3161 timestamp token against the given encrypted digest |
| 160 | // from the primary signature. |
| 161 | func VerifyMicrosoftToken(token *pkcs7.ContentInfoSignedData, encryptedDigest []byte) (*CounterSignature, error) { |
| 162 | sig, err := token.Content.Verify(nil, false) |
| 163 | if err != nil { |
| 164 | return nil, err |
| 165 | } |
| 166 | content, err := token.Content.ContentInfo.Bytes() |
| 167 | if err != nil { |
| 168 | return nil, err |
| 169 | } |
| 170 | if !bytes.Equal(content, encryptedDigest) { |
| 171 | return nil, errors.New("timestamp does not match the enclosing signature") |
| 172 | } |
| 173 | hash, _ := x509tools.PkixDigestToHash(sig.SignerInfo.DigestAlgorithm) |
| 174 | signingTime, err := sig.SignerInfo.SigningTime() |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | return &CounterSignature{ |
| 179 | Signature: sig, |
| 180 | Hash: hash, |
| 181 | SigningTime: signingTime, |
| 182 | }, nil |
| 183 | } |