2023-09-21 08:50:18 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
|
|
|
package measure
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2024-02-05 06:06:48 -05:00
|
|
|
"crypto"
|
2023-09-21 08:50:18 -04:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
|
2024-02-05 06:06:48 -05:00
|
|
|
"github.com/foxboron/go-uefi/authenticode"
|
2023-09-21 08:50:18 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Authentihash returns the PE/COFF hash / Authentihash of a file.
|
2024-02-05 06:06:48 -05:00
|
|
|
func Authentihash(r io.Reader, h crypto.Hash) ([]byte, error) {
|
|
|
|
readerAt, err := getReaderAt(r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to get readerAt: %v", err)
|
2023-09-21 08:50:18 -04:00
|
|
|
}
|
|
|
|
|
2024-02-05 06:06:48 -05:00
|
|
|
bin, err := authenticode.Parse(readerAt)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse pe file: %v", err)
|
|
|
|
}
|
|
|
|
return bin.Hash(h), nil
|
|
|
|
}
|
2023-09-21 08:50:18 -04:00
|
|
|
|
2024-02-05 06:06:48 -05:00
|
|
|
func getReaderAt(r io.Reader) (io.ReaderAt, error) {
|
|
|
|
if ra, ok := r.(io.ReaderAt); ok {
|
|
|
|
return ra, nil
|
|
|
|
}
|
2023-09-21 08:50:18 -04:00
|
|
|
|
2024-02-05 06:06:48 -05:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if _, err := buf.ReadFrom(r); err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to read pe file: %v", err)
|
|
|
|
}
|
|
|
|
return bytes.NewReader(buf.Bytes()), nil
|
2023-09-21 08:50:18 -04:00
|
|
|
}
|