Debian Codegraph @

lib/authenticode/powershell.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 "bufio"
21 "bytes"
22 "context"
23 "crypto"
24 "crypto/hmac"
25 "encoding/base64"
26 "encoding/binary"
27 "errors"
28 "fmt"
29 "io"
30 "path/filepath"
31 "strings"
32 "unicode/utf16"
33
34 "github.com/sassoftware/relic/v7/lib/binpatch"
35 "github.com/sassoftware/relic/v7/lib/certloader"
36 "github.com/sassoftware/relic/v7/lib/pkcs7"
37 "github.com/sassoftware/relic/v7/lib/pkcs9"
38 "github.com/sassoftware/relic/v7/lib/x509tools"
39 "github.com/sassoftware/relic/v7/signers/sigerrors"
40 )
41
42 // Type of signature formatting used for different PowerShell file formats
43 type PsSigStyle int
44
45 const (
46 // "Hash" style used by e.g. .ps1 files
47 SigStyleHash PsSigStyle = iota + 1
48 // XML style used by e.g. .ps1xml files
49 SigStyleXML
50 // C# style used by .mof files
51 SigStyleC
52 )
53
54 var psExtMap = map[string]PsSigStyle{
55 ".ps1": SigStyleHash,
56 ".ps1xml": SigStyleXML,
57 ".psc1": SigStyleXML,
58 ".psd1": SigStyleHash,
59 ".psm1": SigStyleHash,
60 ".cdxml": SigStyleXML,
61 ".mof": SigStyleC,
62 }
63
64 const psBegin = "SIG # Begin signature block"
65 const psEnd = "SIG # End signature block"
66
67 type sigStyle struct{ start, end string }
68
69 var psStyles = map[PsSigStyle]sigStyle{
70 SigStyleHash: {"# ", ""},
71 SigStyleXML: {"<!-- ", " -->"},
72 SigStyleC: {"/* ", " */"},
73 }
74
75 // Get the PowerShell signature style for a filename or extension
76 func GetSigStyle(filename string) (PsSigStyle, bool) {
77 style, ok := psExtMap[filepath.Ext(filename)]
78 return style, ok
79 }
80
81 // Return all supported PowerShell signature styles
82 func AllSigStyles() []string {
83 var ret []string
84 for k := range psExtMap {
85 ret = append(ret, k)
86 }
87 return ret
88 }
89
90 type PsDigest struct {
91 Imprint []byte
92 HashFunc crypto.Hash
93 TextSize, SigSize int64
94 SigStyle PsSigStyle
95 IsUtf16 bool
96 }
97
98 // Digest a PowerShell script from a stream, returning the sum and the length of the digested bytes.
99 //
100 // PowerShell scripts are digested in UTF-16-LE format so, unless already in
101 // that format, the text is converted first. Existing signatures are discarded.
102 func DigestPowershell(r io.Reader, style PsSigStyle, hash crypto.Hash) (*PsDigest, error) {
103 si, ok := psStyles[style]
104 if !ok {
105 return nil, errors.New("invalid powershell signature style")
106 }
107 br := bufio.NewReader(r)
108 isUtf16, first, _ := detectUtf16(br, si.start, si.end)
109 d := hash.New()
110 var textSize, sigSize int64
111 var saved string
112 for {
113 line, err := readLine(br, isUtf16)
114 if err != nil && err != io.EOF {
115 return nil, err
116 }
117 if line == first {
118 // remove EOL from previous line
119 if isUtf16 {
120 saved = saved[:len(saved)-4]
121 sigSize = 4
122 } else {
123 saved = saved[:len(saved)-2]
124 sigSize = 2
125 }
126 // count the size of the signature
127 sigSize += int64(len(line))
128 n, err := io.Copy(io.Discard, br)
129 if err != nil {
130 return nil, err
131 }
132 sigSize += n
133 break
134 } else {
135 _ = writeUtf16(d, saved, isUtf16)
136 textSize += int64(len(saved))
137 saved = line
138 }
139 if err == io.EOF {
140 break
141 }
142 }
143 _ = writeUtf16(d, saved, isUtf16)
144 textSize += int64(len(saved))
145 return &PsDigest{d.Sum(nil), hash, textSize, sigSize, style, isUtf16}, nil
146 }
147
148 func detectUtf16(br *bufio.Reader, start, end string) (bool, string, string) {
149 first := start + psBegin + end + "\r\n"
150 last := start + psEnd + end + "\r\n"
151 if bom, err := br.Peek(2); err == nil && bom[0] == 0xff && bom[1] == 0xfe {
152 // UTF-16-LE
153 return true, toUtf16(first), toUtf16(last)
154 }
155 return false, first, last
156 }
157
158 type PowershellSignature struct {
159 pkcs9.TimestampedSignature
160 OpusInfo *SpcSpOpusInfo
161 HashFunc crypto.Hash
162 }
163
164 // Verify a PowerShell script. The signature "style" must already have been
165 // determined by calling GetSigStyle
166 func VerifyPowershell(r io.ReadSeeker, style PsSigStyle, skipDigests bool) (*PowershellSignature, error) {
167 si, ok := psStyles[style]
168 if !ok {
169 return nil, errors.New("invalid powershell signature style")
170 }
171 br := bufio.NewReader(r)
172 isUtf16, first, last := detectUtf16(br, si.start, si.end)
173 found := false
174 var textSize int64
175 var pkcsb bytes.Buffer
176 for {
177 line, err := readLine(br, isUtf16)
178 if err == io.EOF && !found {
179 return nil, sigerrors.NotSignedError{Type: "powershell document"}
180 } else if err != nil {
181 return nil, err
182 }
183 if found && line == last {
184 break
185 } else if found {
186 lstr := string(line)
187 if isUtf16 {
188 lstr = fromUtf16(line)
189 }
190 if !strings.HasPrefix(lstr, si.start) || !strings.HasSuffix(lstr, si.end+"\r\n") {
191 return nil, errors.New("malformed powershell signature")
192 }
193 i := len(si.start)
194 j := len(lstr) - len(si.end) - 2
195 lder, err := base64.StdEncoding.DecodeString(lstr[i:j])
196 if err != nil {
197 return nil, err
198 }
199 pkcsb.Write(lder)
200 } else if line == first {
201 // remove preceding \r\n from size
202 if isUtf16 {
203 textSize -= 4
204 } else {
205 textSize -= 2
206 }
207 found = true
208 } else {
209 textSize += int64(len(line))
210 }
211 }
212 psd, err := pkcs7.Unmarshal(pkcsb.Bytes())
213 if err != nil {
214 return nil, err
215 }
216 if !psd.Content.ContentInfo.ContentType.Equal(OidSpcIndirectDataContent) {
217 return nil, errors.New("not an authenticode signature")
218 }
219 sig, err := psd.Content.Verify(nil, false)
220 if err != nil {
221 return nil, err
222 }
223 ts, err := pkcs9.VerifyOptionalTimestamp(sig)
224 if err != nil {
225 return nil, err
226 }
227 indirect := new(SpcIndirectDataContentMsi)
228 if err := psd.Content.ContentInfo.Unmarshal(indirect); err != nil {
229 return nil, err
230 }
231 hash, err := x509tools.PkixDigestToHashE(indirect.MessageDigest.DigestAlgorithm)
232 if err != nil {
233 return nil, err
234 }
235 if !skipDigests {
236 if _, err := r.Seek(0, 0); err != nil {
237 return nil, err
238 }
239 digest, err := DigestPowershell(r, style, hash)
240 if err != nil {
241 return nil, err
242 }
243 if !hmac.Equal(digest.Imprint, indirect.MessageDigest.Digest) {
244 return nil, fmt.Errorf("digest mismatch: %x != %x", digest.Imprint, indirect.MessageDigest.Digest)
245 }
246 }
247 opus, err := GetOpusInfo(ts.SignerInfo)
248 if err != nil {
249 return nil, err
250 }
251 pss := &PowershellSignature{
252 TimestampedSignature: ts,
253 HashFunc: hash,
254 OpusInfo: opus,
255 }
256 return pss, nil
257 }
258
259 // Sign a previously digested PowerShell script and return the Authenticode structure
260 func (pd *PsDigest) Sign(ctx context.Context, cert *certloader.Certificate, params *OpusParams) (*binpatch.PatchSet, *pkcs9.TimestampedSignature, error) {
261 ts, err := SignSip(ctx, pd.Imprint, pd.HashFunc, psSipInfo, cert, params)
262 if err != nil {
263 return nil, nil, err
264 }
265 patch, err := pd.MakePatch(ts.Raw)
266 if err != nil {
267 return nil, nil, err
268 }
269 return patch, ts, nil
270 }
271
272 // Create a patchset that will add or replace the signature on the digested script
273 func (pd *PsDigest) MakePatch(sig []byte) (*binpatch.PatchSet, error) {
274 si, ok := psStyles[pd.SigStyle]
275 if !ok {
276 return nil, errors.New("invalid powershell signature style")
277 }
278 var buf bytes.Buffer
279 buf.WriteString("\r\n" + si.start + psBegin + si.end + "\r\n")
280 b64 := base64.StdEncoding.EncodeToString(sig)
281 for i := 0; i < len(b64); i += 64 {
282 j := i + 64
283 if j > len(b64) {
284 j = len(b64)
285 }
286 buf.WriteString(si.start + b64[i:j] + si.end + "\r\n")
287 }
288 buf.WriteString(si.start + psEnd + si.end + "\r\n")
289 patch := binpatch.New()
290 var encoded []byte
291 if pd.IsUtf16 {
292 encoded = []byte(toUtf16(buf.String()))
293 } else {
294 encoded = buf.Bytes()
295 }
296 patch.Add(pd.TextSize, int64(pd.SigSize), encoded)
297 return patch, nil
298 }
299
300 func readLine(br *bufio.Reader, isUtf16 bool) (string, error) {
301 line, err := br.ReadString('\n')
302 if isUtf16 && err == nil {
303 // \n\0
304 var zero byte
305 zero, err = br.ReadByte()
306 if zero != 0 {
307 return "", errors.New("malformed utf16")
308 }
309 line += "\x00"
310 }
311 return line, err
312 }
313
314 // Convert UTF8 to UTF-16-LE
315 func toUtf16(x string) string {
316 runes := utf16.Encode([]rune(x))
317 buf := bytes.NewBuffer(make([]byte, 0, 2*len(runes)))
318 _ = binary.Write(buf, binary.LittleEndian, runes)
319 return buf.String()
320 }
321
322 // Convert UTF8 to UTF-16-LE and write it to "d"
323 func writeUtf16(d io.Writer, x string, isUtf16 bool) error {
324 if isUtf16 {
325 _, err := d.Write([]byte(x))
326 return err
327 }
328 runes := utf16.Encode([]rune(x))
329 return binary.Write(d, binary.LittleEndian, runes)
330 }
331
332 // Convert UTF-16-LE to UTF8
333 func fromUtf16(x string) string {
334 runes := make([]uint16, len(x)/2)
335 _ = binary.Read(bytes.NewReader([]byte(x)), binary.LittleEndian, runes)
336 return string(utf16.Decode(runes))
337 }