Debian Codegraph @

lib/authenticode/pedigest.go

raw symbols SCIP
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 "debug/pe"
23 "encoding/binary"
24 "errors"
25 "fmt"
26 "hash"
27 "io"
28 "io/ioutil"
29 )
30
31 // PE-COFF: https://www.microsoft.com/en-us/download/details.aspx?id=19509
32 // PE Authenticode: http://msdn.microsoft.com/en-us/windows/hardware/gg463180.aspx
33
34 type PEDigest struct {
35 OrigSize int64
36 CertStart int64
37 Imprint []byte
38 PageHashes []byte
39 Hash crypto.Hash
40 markers *peHeaderValues
41 }
42
43 const dosHeaderSize = 64
44
45 // Calculate a digest (message imprint) over a PE image. Returns a structure
46 // that can be used to sign the imprint and produce a binary patch to apply the
47 // signature.
48 func DigestPE(r io.Reader, hash crypto.Hash, doPageHash bool) (*PEDigest, error) {
49 // Read and buffer all the headers
50 buf := bytes.NewBuffer(make([]byte, 0, 4096))
51 peStart, err := readDosHeader(r, buf)
52 if err != nil {
53 return nil, err
54 }
55 if _, err := io.CopyN(buf, r, peStart-dosHeaderSize); err != nil {
56 return nil, err
57 }
58 fh, err := readCoffHeader(r, buf)
59 if err != nil {
60 return nil, err
61 }
62 hvals, err := readOptHeader(r, buf, peStart, fh)
63 if err != nil {
64 return nil, err
65 }
66 sections, err := readSections(r, buf, fh, hvals)
67 if err != nil {
68 return nil, err
69 }
70 digester := setupDigester(hash, buf.Bytes(), hvals, sections, doPageHash)
71 // Hash sections
72 nextSection := hvals.sizeOfHdr
73 for i, sh := range sections {
74 if sh.SizeOfRawData == 0 {
75 continue
76 }
77 if int64(sh.PointerToRawData) != nextSection {
78 return nil, fmt.Errorf("PE section %d begins at 0x%x but expected 0x%x", i, sh.PointerToRawData, nextSection)
79 }
80 if err := digester.section(r, sh); err != nil {
81 return nil, err
82 }
83 nextSection += int64(sh.SizeOfRawData)
84 }
85 // Hash trailer after the sections and cert table
86 origSize, err := readTrailer(r, digester.imageDigest, nextSection, hvals.certStart, hvals.certSize)
87 if err != nil {
88 return nil, err
89 }
90 certStart := origSize
91 if n := origSize % 8; n != 0 {
92 // pad to 8 bytes
93 padding := 8 - n
94 digester.imageDigest.Write(make([]byte, padding))
95 certStart += padding
96 }
97 imprint, pagehashes, err := digester.finish()
98 if err != nil {
99 return nil, err
100 }
101 return &PEDigest{origSize, certStart, imprint, pagehashes, hash, hvals}, nil
102 }
103
104 type imageHasher struct {
105 hashFunc crypto.Hash
106 imageDigest hash.Hash
107 pageHashes []byte
108 zeroPage []byte
109 pageBuf []byte
110 doPageHash bool
111 lastPage uint32
112 }
113
114 func setupDigester(hash crypto.Hash, header []byte, hvals *peHeaderValues, sections []pe.SectionHeader32, doPageHash bool) *imageHasher {
115 imageDigest := hash.New()
116 imageDigest.Write(header)
117 h := &imageHasher{hashFunc: hash, imageDigest: imageDigest, doPageHash: doPageHash}
118 if doPageHash {
119 h.zeroPage = make([]byte, hvals.pageSize) // full page of zeroes, for padding
120 h.pageBuf = make([]byte, hvals.pageSize) // scratch space
121 // make space for all the page hashes
122 pages := 2
123 for _, sh := range sections {
124 spage := (sh.SizeOfRawData + hvals.pageSize - 1) / hvals.pageSize
125 pages += int(spage)
126 }
127 h.pageHashes = make([]byte, 0, pages*(4+hash.Size()))
128 // the first page is the headers padded out to a full page with the
129 // signature bits snipped out in the same way as for the regular
130 // imprint. the padding is done based on the full size of the
131 // header, so the data being hashed is 12 bytes short of a full
132 // page
133 removed := int(hvals.sizeOfHdr) - len(header)
134 h.addPageHash(0, header, removed)
135 }
136 return h
137 }
138
139 func (h *imageHasher) section(r io.Reader, sh pe.SectionHeader32) error {
140 if !h.doPageHash {
141 _, err := io.CopyN(h.imageDigest, r, int64(sh.SizeOfRawData))
142 return err
143 }
144 position := sh.PointerToRawData
145 remaining := int(sh.SizeOfRawData)
146 for remaining > 0 {
147 n := remaining
148 if n > len(h.pageBuf) {
149 n = len(h.pageBuf)
150 }
151 buf := h.pageBuf[:n]
152 if _, err := io.ReadFull(r, buf); err != nil {
153 return err
154 }
155 h.imageDigest.Write(buf)
156 h.addPageHash(position, buf, 0)
157 position += uint32(n)
158 remaining -= n
159 h.lastPage = position
160 }
161 return nil
162 }
163
164 func (h *imageHasher) finish() ([]byte, []byte, error) {
165 sum := h.imageDigest.Sum(nil)
166 if h.doPageHash {
167 h.addPageHash(h.lastPage, nil, 0)
168 }
169 return sum, h.pageHashes, nil
170 }
171
172 func (h *imageHasher) addPageHash(offset uint32, blob []byte, removed int) {
173 var obytes [4]byte
174 binary.LittleEndian.PutUint32(obytes[:], offset)
175 h.pageHashes = append(h.pageHashes, obytes[:]...)
176 if len(blob) == 0 {
177 // last "page" has a null digest
178 h.pageHashes = append(h.pageHashes, make([]byte, h.hashFunc.Size())...)
179 return
180 }
181 d := h.hashFunc.New()
182 d.Write(blob)
183 needzero := len(h.zeroPage) - len(blob) - removed
184 d.Write(h.zeroPage[:needzero])
185 h.pageHashes = d.Sum(h.pageHashes)
186 }
187
188 func readDosHeader(r io.Reader, d io.Writer) (int64, error) {
189 dosheader, err := readAndHash(r, d, dosHeaderSize)
190 if err != nil {
191 return 0, err
192 } else if dosheader[0] != 'M' || dosheader[1] != 'Z' {
193 return 0, errors.New("not a PE file")
194 }
195 return int64(binary.LittleEndian.Uint32(dosheader[0x3c:])), nil
196 }
197
198 func readCoffHeader(r io.Reader, d io.Writer) (*pe.FileHeader, error) {
199 if magic, err := readAndHash(r, d, 4); err != nil {
200 return nil, err
201 } else if magic[0] != 'P' || magic[1] != 'E' || magic[2] != 0 || magic[3] != 0 {
202 return nil, errors.New("not a PE file")
203 }
204
205 buf, err := readAndHash(r, d, 20)
206 if err != nil {
207 return nil, err
208 }
209 hdr := new(pe.FileHeader)
210 if err := binaryReadBytes(buf, hdr); err != nil {
211 return nil, err
212 }
213 return hdr, nil
214 }
215
216 const (
217 // https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header-image-only
218 optHeaderMagicPE32 = 0x10b
219 optHeaderMagicPE32Plus = 0x20b
220
221 // https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types
222 imageFileMachineAlpha = 0x184
223 imageFileMachineAlpha64 = 0x284
224 )
225
226 func readOptHeader(r io.Reader, d io.Writer, peStart int64, fh *pe.FileHeader) (*peHeaderValues, error) {
227 hvals := new(peHeaderValues)
228 hvals.peStart = peStart
229 // https://devblogs.microsoft.com/oldnewthing/20210510-00/
230 switch fh.Machine {
231 case pe.IMAGE_FILE_MACHINE_IA64, imageFileMachineAlpha, imageFileMachineAlpha64:
232 hvals.pageSize = 8192
233 default:
234 hvals.pageSize = 4096
235 }
236 buf := make([]byte, fh.SizeOfOptionalHeader)
237 if _, err := io.ReadFull(r, buf); err != nil {
238 return nil, err
239 }
240 // locate the bits that need to be omitted from hash
241 cksumStart := 64
242 cksumEnd := cksumStart + 4
243 var dd4Start int64
244 var dd pe.DataDirectory
245 optMagic := binary.LittleEndian.Uint16(buf[:2])
246 switch optMagic {
247 case optHeaderMagicPE32:
248 // PE32
249 var opt pe.OptionalHeader32
250 if err := binaryReadBytes(buf, &opt); err != nil {
251 return nil, err
252 }
253 if opt.NumberOfRvaAndSizes < 5 {
254 return nil, errors.New("PE header did not leave room for signature")
255 }
256 dd = opt.DataDirectory[4]
257 dd4Start = 128
258 hvals.sizeOfHdr = int64(opt.SizeOfHeaders)
259 hvals.fileAlign = opt.FileAlignment
260 case optHeaderMagicPE32Plus:
261 // PE32+
262 var opt pe.OptionalHeader64
263 if err := binaryReadBytes(buf, &opt); err != nil {
264 return nil, err
265 }
266 if opt.NumberOfRvaAndSizes < 5 {
267 return nil, errors.New("PE header did not leave room for signature")
268 }
269 dd = opt.DataDirectory[4]
270 dd4Start = 144
271 hvals.sizeOfHdr = int64(opt.SizeOfHeaders)
272 hvals.fileAlign = opt.FileAlignment
273 default:
274 return nil, errors.New("unrecognized optional header magic")
275 }
276 dd4End := dd4Start + 8
277 hvals.certStart = int64(dd.VirtualAddress)
278 hvals.certSize = int64(dd.Size)
279 hvals.secTblStart = peStart + 24 + int64(fh.SizeOfOptionalHeader)
280 _, _ = d.Write(buf[:cksumStart])
281 _, _ = d.Write(buf[cksumEnd:dd4Start])
282 _, _ = d.Write(buf[dd4End:])
283 hvals.posDDCert = peStart + 24 + dd4Start
284 return hvals, nil
285 }
286
287 func readSections(r io.Reader, d io.Writer, fh *pe.FileHeader, hvals *peHeaderValues) ([]pe.SectionHeader32, error) {
288 // read and hash section table
289 sections := make([]pe.SectionHeader32, fh.NumberOfSections)
290 size := int(fh.NumberOfSections) * 40
291 secTblEnd := hvals.secTblStart + int64(size)
292 if secTblEnd > hvals.sizeOfHdr {
293 return nil, errors.New("PE section overlaps section table")
294 }
295 if buf, err := readAndHash(r, d, size); err != nil {
296 return nil, err
297 } else if err := binaryReadBytes(buf, sections); err != nil {
298 return nil, err
299 }
300 // look for start of first section and check for overlap
301 for i, section := range sections {
302 if section.SizeOfRawData == 0 {
303 continue
304 }
305 if p := int64(section.PointerToRawData); p < secTblEnd {
306 return nil, fmt.Errorf("PE section %d at 0x%x overlaps section table at 0x%x", i, p, secTblEnd)
307 } else if p < hvals.sizeOfHdr {
308 // some samples have a SizeOfHeaders that goes past the start of the first section
309 hvals.sizeOfHdr = p
310 }
311 // Adjust any sections that are not properly aligned
312 sections[i].SizeOfRawData = align32(section.SizeOfRawData, hvals.fileAlign)
313 }
314 // hash the padding after the section table
315 if _, err := io.CopyN(d, r, hvals.sizeOfHdr-secTblEnd); err != nil {
316 return nil, err
317 }
318 return sections, nil
319 }
320
321 func readTrailer(r io.Reader, d io.Writer, lastSection, certStart, certSize int64) (int64, error) {
322 if certSize == 0 {
323 n, err := io.Copy(d, r)
324 return lastSection + n, err
325 }
326 if certStart < lastSection {
327 return 0, errors.New("existing signature overlaps with PE sections")
328 }
329 if _, err := io.CopyN(d, r, certStart-lastSection); err != nil {
330 return 0, err
331 }
332 if _, err := io.CopyN(ioutil.Discard, r, certSize); err != nil {
333 return 0, err
334 }
335 if n, _ := io.Copy(ioutil.Discard, r); n > 0 {
336 return 0, errors.New("trailing garbage after existing certificate")
337 }
338 return certStart, nil
339 }
340
341 type peHeaderValues struct {
342 // start of PE header
343 peStart int64
344 // file offset to the data directory entry for the cert table, in the optional header
345 posDDCert int64
346 // file offset to the end of the optional header and the start of the section table
347 secTblStart int64
348 // size of all headers plus padding
349 sizeOfHdr int64
350 // architecture page size
351 pageSize uint32
352 // section alignment in file
353 fileAlign uint32
354 // file offset and size of the certificate table
355 certStart, certSize int64
356 }