Debian Codegraph @

command/crypto/winpe/winpe.go

raw symbols SCIP
1 package winpe
2
3 import (
4 "debug/pe"
5 "encoding/asn1"
6 "encoding/binary"
7 "encoding/pem"
8 "io"
9 "os"
10 "path"
11
12 "github.com/pkg/errors"
13 "github.com/smallstep/cli/errs"
14 "github.com/urfave/cli"
15 "go.mozilla.org/pkcs7"
16 )
17
18 // Command returns the winpe subcommand.
19 func Command() cli.Command {
20 return cli.Command{
21 Name: "winpe",
22 Usage: "extract certificates and verify Windows Portable Executable files",
23 UsageText: "step crypto winpe <subcommand> [arguments] [global-flags] [subcommand-flags]",
24 Description: `**step crypto winpe** command group provides facilities to extract certificates and
25 verify Windows Portable Executable files.
26
27 ## EXAMPLES
28
29 Extract all certificates and output in JSON format:
30 '''
31 step crypto winpe extract my.exe | step certificate inspect --format json --bundle
32 '''`,
33 Subcommands: cli.Commands{
34 extractCommand(),
35 },
36 }
37 }
38
39 var ErrCodeSignCertsNoCertificateTableFound = errors.New("No Certificate Table found")
40
41 func extractCommand() cli.Command {
42 return cli.Command{
43 Name: "extract",
44 Action: cli.ActionFunc(extractPEAction),
45 Usage: "extract certificates from Windows Portable Executable files",
46 UsageText: `**step crypto winpe extract** <file>`,
47 Description: `**step crypto winpe extract** extract certificate from a Windows Portable Executable file in PEM format.
48
49 For examples, see **step help crypto winpe**.
50
51 ## POSITIONAL ARGUMENTS
52
53 <file>
54 : The path to a Windows Portable Executable file`,
55 }
56 }
57
58 func extractPEAction(ctx *cli.Context) error {
59 if err := errs.NumberOfArguments(ctx, 1); err != nil {
60 return err
61 }
62
63 return extractPE(path.Clean(ctx.Args().Get(0)))
64 }
65
66 func extractPE(filename string) error {
67 file, err := os.Open(filename)
68 if err != nil {
69 return errors.Wrapf(err, "error opening %s", filename)
70 }
71 defer file.Close()
72
73 f, err := pe.NewFile(file)
74 if err != nil {
75 return errors.Wrap(err, "Unable to open the PE file")
76 }
77 defer f.Close()
78
79 var (
80 buff []byte
81 ob *asn1.ObjectIdentifier
82 )
83
84 switch header := f.OptionalHeader.(type) {
85 case *pe.OptionalHeader32:
86 buff, ob, err = codeSignCertsParseHeader32(header, file)
87 case *pe.OptionalHeader64:
88 buff, ob, err = codeSignCertsParseHeader64(header, file)
89 default:
90 err = errors.Errorf("Header of type %T is not supported", header)
91 }
92
93 if err != nil {
94 return errors.Wrap(err, "Error parsing the executable's headers")
95 }
96
97 err = codeSignCertsParseCertificateTable(buff, ob, os.Stdout)
98 if err != nil {
99 return errors.Wrap(err, "Error to parse the certificate table from the executable's table")
100 }
101
102 return nil
103 }
104
105 // Wrapper Functions
106 // PE headers can be written by 64 bits architectures or 32 bits architectures.
107 // 32 bits is IMHO more spread out because it's backward compatible with 64 bits.
108 // I don't think it changes the fact that the program can for a 64 bits arch and the headers 32 bits.
109 func codeSignCertsParseHeader64(header *pe.OptionalHeader64, file io.ReaderAt) ([]byte, *asn1.ObjectIdentifier, error) {
110 return codeSignCertsExtractCerts(header.DataDirectory[4], file)
111 }
112 func codeSignCertsParseHeader32(header *pe.OptionalHeader32, file io.ReaderAt) ([]byte, *asn1.ObjectIdentifier, error) {
113 return codeSignCertsExtractCerts(header.DataDirectory[4], file)
114 }
115
116 func codeSignCertsExtractCerts(header pe.DataDirectory, file io.ReaderAt) ([]byte, *asn1.ObjectIdentifier, error) {
117 // The certificate table is the 5th header: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#file-headers
118 if header.VirtualAddress == 0 {
119 return nil, nil, ErrCodeSignCertsNoCertificateTableFound
120 }
121
122 // The payload starts 8 bytes after the header's virtual address value
123 // https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#file-headers
124 // 4 bytes: Specifies the length of the attribute certificate entry.
125 // 2 bytes: Contains the certificate version number.
126 // 2 bytes: Specifies the type of content in bCertificate.
127 start := header.VirtualAddress + 8
128 stop := start + (header.Size - 8) // the attribute Size is the same as what's in the 4 bytes at VirtualAddress, removing 8 bytes since they are added to the VirtualAddressValue
129 size := stop - start
130
131 certType, err := ExtractReadAt(file, 2, int64(header.VirtualAddress+6))
132 if err != nil {
133 return nil, nil, errors.Wrap(err, "Error to extract wCertificateType")
134 }
135
136 // 0x0002 WIN_CERT_TYPE_PKCS_SIGNED_DATA Certificate contains a PKCS#7 SignedData structure
137 if t := binary.LittleEndian.Uint16(certType); t != 2 {
138 return nil, nil, errors.Wrapf(err, "wCertificateType of %d is not supported", t)
139 }
140
141 buff, err := ExtractReadAt(file, int(size), int64(start))
142 if err != nil {
143 return nil, nil, errors.Wrap(err, "Error reading certificate table first entry")
144 }
145
146 ct := &codeSignCertsCertificateTable{}
147 _, err = asn1.Unmarshal(buff, ct)
148 if err != nil {
149 return nil, nil, errors.Wrap(err, "Error unmarshaling certificate table from ASN.1")
150 }
151
152 return buff, &ct.Identifier, nil
153 }
154
155 type codeSignCertsCertificateTable struct {
156 Identifier asn1.ObjectIdentifier
157 RawCertificates asn1.RawValue
158 }
159
160 func ExtractReadAt(reader io.ReaderAt, l int, off int64) ([]byte, error) {
161 buff := make([]byte, l)
162
163 read, err := reader.ReadAt(buff, off)
164 if err != nil {
165 if err != io.EOF {
166 return nil, err
167 }
168 }
169
170 if read != len(buff) {
171 return nil, io.ErrShortWrite
172 }
173
174 return buff, nil
175 }
176
177 func codeSignCertsParseCertificateTable(buff []byte, ob *asn1.ObjectIdentifier, writer io.Writer) error {
178 // The signed data is OID 1.2.840.113549.1.7.2
179 // - https://www.alvestrand.no/objectid/1.2.840.113549.1.7.2.html
180 // - 0x0002 WIN_CERT_TYPE_PKCS_SIGNED_DATA Certificate contains a PKCS#7 SignedData structure
181 if ob.Equal(asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2}) {
182 p7, err := pkcs7.Parse(buff)
183 if err != nil {
184 return errors.Wrap(err, "Error parsing Certificate Table entry to PKCS7")
185 }
186
187 for _, cert := range p7.Certificates {
188 block := &pem.Block{
189 Type: "CERTIFICATE",
190 Bytes: cert.Raw,
191 }
192
193 err := pem.Encode(writer, block)
194 if err != nil {
195 return errors.Wrap(err, "Error encoding certificate to PEM")
196 }
197 }
198
199 return nil
200 }
201
202 return errors.Errorf("Certificate Table's entry type of %s is not supported\n", ob.String())
203 }