| 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 authenticode |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "crypto" |
| 22 | "crypto/hmac" |
| 23 | "encoding/asn1" |
| 24 | "encoding/binary" |
| 25 | "errors" |
| 26 | "fmt" |
| 27 | "io" |
| 28 | |
| 29 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 30 | "github.com/sassoftware/relic/v7/lib/pkcs9" |
| 31 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 32 | "github.com/sassoftware/relic/v7/signers/sigerrors" |
| 33 | ) |
| 34 | |
| 35 | type PESignature struct { |
| 36 | pkcs9.TimestampedSignature |
| 37 | Indirect *SpcIndirectDataContentPe |
| 38 | OpusInfo *SpcSpOpusInfo |
| 39 | ImageHashFunc crypto.Hash |
| 40 | PageHashes []byte |
| 41 | PageHashFunc crypto.Hash |
| 42 | } |
| 43 | |
| 44 | // Extract and verify the signature from a PE/COFF image file. Does not check X509 chains. |
| 45 | func VerifyPE(r io.ReadSeeker, skipDigests bool) ([]PESignature, error) { |
| 46 | hvals, err := findSignatures(r) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } else if hvals.certSize == 0 { |
| 50 | return nil, sigerrors.NotSignedError{Type: "PECOFF"} |
| 51 | } |
| 52 | // Read certificate table |
| 53 | sigblob := make([]byte, hvals.certSize) |
| 54 | if _, err := r.Seek(hvals.certStart, 0); err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | if _, err := io.ReadFull(r, sigblob); err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | // Parse and verify signatures |
| 61 | if skipDigests { |
| 62 | r = nil |
| 63 | } |
| 64 | return checkSignatures(sigblob, r) |
| 65 | } |
| 66 | |
| 67 | func findSignatures(r io.ReadSeeker) (*peHeaderValues, error) { |
| 68 | if _, err := r.Seek(0, 0); err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | d := io.Discard |
| 72 | peStart, err := readDosHeader(r, d) |
| 73 | if err != nil { |
| 74 | return nil, err |
| 75 | } |
| 76 | if _, err := r.Seek(peStart, 0); err != nil { |
| 77 | return nil, err |
| 78 | } |
| 79 | fh, err := readCoffHeader(r, d) |
| 80 | if err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | return readOptHeader(r, d, peStart, fh) |
| 84 | } |
| 85 | |
| 86 | func checkSignatures(blob []byte, image io.ReadSeeker) ([]PESignature, error) { |
| 87 | values := make(map[crypto.Hash][]byte) |
| 88 | phvalues := make(map[crypto.Hash][]byte) |
| 89 | allhashes := make(map[crypto.Hash]bool) |
| 90 | sigs := make([]PESignature, 0, 1) |
| 91 | for len(blob) != 0 { |
| 92 | if len(blob) < 4 { |
| 93 | return nil, errors.New("invalid certificate table") |
| 94 | } |
| 95 | wLen := binary.LittleEndian.Uint32(blob[:4]) |
| 96 | end := (int(wLen) + 7) / 8 * 8 |
| 97 | size := int(wLen) - 8 |
| 98 | if end > len(blob) || size < 0 { |
| 99 | return nil, errors.New("invalid certificate table") |
| 100 | } |
| 101 | cert := blob[8 : 8+size] |
| 102 | blob = blob[end:] |
| 103 | |
| 104 | sig, err := checkSignature(cert) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | allhashes[sig.ImageHashFunc] = true |
| 109 | if len(sig.PageHashes) > 0 { |
| 110 | phvalues[sig.PageHashFunc] = sig.PageHashes |
| 111 | allhashes[sig.PageHashFunc] = true |
| 112 | } |
| 113 | sigs = append(sigs, *sig) |
| 114 | imageDigest := sig.Indirect.MessageDigest.Digest |
| 115 | if existing := values[sig.ImageHashFunc]; existing == nil { |
| 116 | values[sig.ImageHashFunc] = imageDigest |
| 117 | } else if !hmac.Equal(imageDigest, existing) { |
| 118 | // they can't both be right... |
| 119 | return nil, fmt.Errorf("digest mismatch: %x != %x", imageDigest, existing) |
| 120 | } |
| 121 | } |
| 122 | if image == nil { |
| 123 | return sigs, nil |
| 124 | } |
| 125 | for hash := range allhashes { |
| 126 | imagehash := values[hash] |
| 127 | pagehashes := phvalues[hash] |
| 128 | if _, err := image.Seek(0, 0); err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | doPageHashes := len(pagehashes) > 0 |
| 132 | digest, err := DigestPE(image, hash, doPageHashes) |
| 133 | if err != nil { |
| 134 | return sigs, err |
| 135 | } |
| 136 | if imagehash != nil && !hmac.Equal(digest.Imprint, imagehash) { |
| 137 | return sigs, fmt.Errorf("digest mismatch: %x != %x", digest.Imprint, imagehash) |
| 138 | } |
| 139 | if pagehashes != nil && !hmac.Equal(digest.PageHashes, pagehashes) { |
| 140 | return sigs, fmt.Errorf("page hash mismatch") |
| 141 | } |
| 142 | } |
| 143 | return sigs, nil |
| 144 | } |
| 145 | |
| 146 | func checkSignature(der []byte) (*PESignature, error) { |
| 147 | psd, err := pkcs7.Unmarshal(der) |
| 148 | if err != nil { |
| 149 | return nil, fmt.Errorf("unmarshaling authenticode signature: %w", err) |
| 150 | } |
| 151 | if !psd.Content.ContentInfo.ContentType.Equal(OidSpcIndirectDataContent) { |
| 152 | return nil, errors.New("not an authenticode signature") |
| 153 | } |
| 154 | sig, err := psd.Content.Verify(nil, false) |
| 155 | if err != nil { |
| 156 | return nil, fmt.Errorf("verifying indirect signature: %w", err) |
| 157 | } |
| 158 | ts, err := pkcs9.VerifyOptionalTimestamp(sig) |
| 159 | if err != nil { |
| 160 | return nil, fmt.Errorf("verifying timestamp: %w", err) |
| 161 | } |
| 162 | indirect := new(SpcIndirectDataContentPe) |
| 163 | if err := psd.Content.ContentInfo.Unmarshal(indirect); err != nil { |
| 164 | return nil, fmt.Errorf("unmarshaling SpcIndirectDataContentPe: %w", err) |
| 165 | } |
| 166 | hash, err := x509tools.PkixDigestToHashE(indirect.MessageDigest.DigestAlgorithm) |
| 167 | if err != nil { |
| 168 | return nil, err |
| 169 | } |
| 170 | opus, err := GetOpusInfo(sig.SignerInfo) |
| 171 | if err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | pesig := &PESignature{ |
| 175 | TimestampedSignature: ts, |
| 176 | Indirect: indirect, |
| 177 | OpusInfo: opus, |
| 178 | ImageHashFunc: hash, |
| 179 | } |
| 180 | if err := readPageHashes(pesig); err != nil { |
| 181 | return nil, err |
| 182 | } |
| 183 | return pesig, nil |
| 184 | } |
| 185 | |
| 186 | func GetOpusInfo(si *pkcs7.SignerInfo) (*SpcSpOpusInfo, error) { |
| 187 | opus := new(SpcSpOpusInfo) |
| 188 | err := si.AuthenticatedAttributes.GetOne(OidSpcSpOpusInfo, opus) |
| 189 | if err == nil { |
| 190 | return opus, nil |
| 191 | } else if errors.As(err, &pkcs7.ErrNoAttribute{}) { |
| 192 | return nil, nil |
| 193 | } |
| 194 | return nil, fmt.Errorf("parsing SpcSpOpusInfo attribute: %w", err) |
| 195 | } |
| 196 | |
| 197 | func readPageHashes(sig *PESignature) error { |
| 198 | serObj := sig.Indirect.Data.Value.File.Moniker |
| 199 | if !bytes.Equal(serObj.ClassID, SpcUUIDPageHashes) { |
| 200 | // not present |
| 201 | return nil |
| 202 | } |
| 203 | // unnecessary SET wrapped around the solitary attribute SEQ |
| 204 | var attrRaw asn1.RawValue |
| 205 | if _, err := asn1.Unmarshal(serObj.SerializedData, &attrRaw); err != nil { |
| 206 | return fmt.Errorf("unmarshaling page hashes: %w", err) |
| 207 | } |
| 208 | var attr SpcAttributePageHashes |
| 209 | if _, err := asn1.Unmarshal(attrRaw.Bytes, &attr); err != nil { |
| 210 | return fmt.Errorf("unmarshaling SpcAttributePageHashes: %w", err) |
| 211 | } |
| 212 | switch { |
| 213 | case attr.Type.Equal(OidSpcPageHashV1): |
| 214 | sig.PageHashFunc = crypto.SHA1 |
| 215 | case attr.Type.Equal(OidSpcPageHashV2): |
| 216 | sig.PageHashFunc = crypto.SHA256 |
| 217 | default: |
| 218 | return errors.New("unknown page hash format") |
| 219 | } |
| 220 | // unnecessary SET wrapped around the octets too |
| 221 | sig.PageHashes = attr.Hashes[0] |
| 222 | if len(sig.PageHashes) == 0 || len(sig.PageHashes)%(4+sig.PageHashFunc.Size()) != 0 { |
| 223 | return errors.New("malformed page hash") |
| 224 | } |
| 225 | return nil |
| 226 | } |