-
Notifications
You must be signed in to change notification settings - Fork 13
/
pkcs7.go
560 lines (476 loc) · 15.3 KB
/
pkcs7.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package pkcs7
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"log"
"math/big"
"time"
"golang.org/x/crypto/cryptobyte"
"golang.org/x/crypto/cryptobyte/asn1"
encasn1 "encoding/asn1"
)
// OID data we need
var (
OIDData = encasn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 1}
OIDSignedData = encasn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2}
OIDDigestAlgorithmSHA256 = encasn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
OIDEncryptionAlgorithmRSA = encasn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
OIDAttributeContentType = encasn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 3}
OIDAttributeMessageDigest = encasn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 4}
OIDAttributeSigningTime = encasn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 5}
)
var (
ErrNoCertificate = errors.New("no valid certificates")
)
// Partially implements RFC2315
func SignPKCS7(signer crypto.Signer, cert *x509.Certificate, oid encasn1.ObjectIdentifier, content []byte) ([]byte, error) {
var contentInfo cryptobyte.Builder
// Attributes
// TODO, not needed for Wincert/UEFI. But we do it anyway
// Original Implementation has:
// - OIDAttributeContentType
// - OIDAttributeSigningTime
// - OIDAttributeMessageDigest
// Hash the authenticated attributes
h := crypto.SHA256.New()
h.Write(content)
attrs := &Attributes{
ContentType: oid,
MessageDigest: h.Sum(nil),
SigningTime: time.Now().UTC(),
}
attributes := attrs.Marshal()
h = crypto.SHA256.New()
h.Write(attributes)
sig, err := signer.Sign(rand.Reader, h.Sum(nil), crypto.SHA256)
if err != nil {
log.Fatal(err)
}
// ContentInfo ::= SEQUENCE
contentInfo.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// contentType ContentType,
b.AddASN1ObjectIdentifier(OIDSignedData)
// content [0] EXPLICIT DEFINED BY contentType OPTIONAL
b.AddASN1(asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
// SignedData ::= SEQUENCE
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// version Version,
b.AddASN1Int64(1)
// DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
// digestAlgorithms DigestAlgorithmIdentifiers,
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
// AlgorithmIdentifier ::= SEQUENCE
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// algorithm OBJECT IDENTIFIER,
// NOTE: Only sha256 hardcoded atm
b.AddASN1ObjectIdentifier(OIDDigestAlgorithmSHA256)
// parameters ANY DEFINED BY algorithm OPTIONAL
b.AddASN1NULL()
})
})
// contentInfo ContentInfo
// ContentInfo ::= SEQUENCE
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// contentType ContentType
b.AddASN1ObjectIdentifier(oid)
// content [0] EXPLICIT DEFINED BY contentType OPTIONAL
if len(content) > 0 && !oid.Equal(OIDData) {
b.AddASN1(asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
b.AddBytes(content)
})
})
}
})
// certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL
b.AddASN1(asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
// b.AddBytes(signer.Raw)
b.AddBytes(cert.Raw)
})
// Not Used
// crls [1] IMPLICIT CertificateRevocationLists OPTIONAL
// signerInfos SignerInfos
// SignerInfos ::= SET OF SignerInfo
// We only have one in Authenticode
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
// SignerInfo ::= SEQUENCE
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// version Version,
b.AddASN1Int64(1)
// issuerAndSerialNumber IssuerAndSerialNumber
// IssuerAndSerialNumber ::= SEQUENCE
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// issuer Name
b.AddBytes(cert.RawIssuer)
// serialNumber CertificateSerialNumber
b.AddASN1BigInt(cert.SerialNumber)
})
// digestAlgorithm DigestAlgorithmIdentifier
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// algorithm OBJECT IDENTIFIER,
// NOTE: Only sha256 hardcoded atm
b.AddASN1ObjectIdentifier(OIDDigestAlgorithmSHA256)
// parameters ANY DEFINED BY algorithm OPTIONAL
b.AddASN1NULL()
})
// authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL
b.AddASN1(asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
attrsOuter := cryptobyte.String(attributes)
var attrsInner cryptobyte.String
attrsOuter.ReadASN1(&attrsInner, asn1.SET)
b.AddBytes(attrsInner)
})
// digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
// algorithm OBJECT IDENTIFIER,
b.AddASN1ObjectIdentifier(OIDEncryptionAlgorithmRSA)
// parameters ANY DEFINED BY algorithm OPTIONAL
b.AddASN1NULL()
})
// encryptedDigest EncryptedDigest
b.AddASN1OctetString(sig)
// unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
// Not used
})
})
})
})
})
return contentInfo.Bytes()
}
// Parse cryptobyte string to pkix.AlgorithmIdentifier
func ParseAlgorithmIdentifier(der *cryptobyte.String) (*pkix.AlgorithmIdentifier, error) {
var ident pkix.AlgorithmIdentifier
var s cryptobyte.String
if !der.ReadASN1(&s, asn1.SEQUENCE) {
return nil, errors.New("no algorithmidentifier")
}
if !s.ReadASN1ObjectIdentifier(&ident.Algorithm) {
return nil, errors.New("missing missing algorithmIdentifier")
}
if s.Empty() {
return &ident, nil
}
var asn1Null cryptobyte.String
if !s.ReadASN1(&asn1Null, asn1.NULL) {
return nil, errors.New("missing missing algorithmIdentifier")
}
// TODO: Support paramters, we don't use it currently
return &ident, nil
}
func hasContentInfo(der *cryptobyte.String) (bool, error) {
check := *der
if !check.ReadASN1(&check, asn1.SEQUENCE) {
return false, errors.New("incorrect input")
}
if !check.PeekASN1Tag(asn1.OBJECT_IDENTIFIER) {
return false, nil
}
return true, nil
}
func ParseContentInfo(der *cryptobyte.String) (oid encasn1.ObjectIdentifier, content cryptobyte.String, err error) {
var s cryptobyte.String
if !der.ReadASN1(&s, asn1.SEQUENCE) {
return nil, nil, errors.New("no contentinfo")
}
if !s.ReadASN1ObjectIdentifier(&oid) {
return nil, nil, errors.New("no contentinfo oid")
}
if !s.ReadOptionalASN1(&content, nil, asn1.Tag(0).ContextSpecific().Constructed()) {
return nil, nil, errors.New("no contentinfo content")
}
return
}
func parseCertificates(der *cryptobyte.String) ([]*x509.Certificate, error) {
var raw cryptobyte.String
if !der.ReadOptionalASN1(&raw, nil, asn1.Tag(0).ContextSpecific().Constructed()) {
return nil, errors.New("no certificates")
}
certs, err := x509.ParseCertificates(raw)
if err != nil {
return nil, fmt.Errorf("failed parsing certificates: %v", err)
}
return certs, nil
}
type issuerAndSerialNumber struct {
RawIssuer []byte
SerialNumber *big.Int
}
func parseIssuerAndSerialNumber(der *cryptobyte.String) (*issuerAndSerialNumber, error) {
// TODO: We don't really use it yet. Expose error
var s cryptobyte.String
var ias issuerAndSerialNumber
var bi big.Int
var issuer cryptobyte.String
if !der.ReadASN1(&s, asn1.SEQUENCE) {
return nil, errors.New("no issuer and serial number")
}
if !s.ReadASN1Element(&issuer, asn1.SEQUENCE) {
return nil, errors.New("not a raw issuer")
}
ias.RawIssuer = issuer
if !s.ReadASN1Integer(&bi) {
return nil, errors.New("no serial number")
}
ias.SerialNumber = &bi
return &ias, nil
}
func parseAttributes(der *cryptobyte.String) (*Attributes, error) {
var attributes Attributes
var attrs cryptobyte.String
var hasAttrs bool
if !der.ReadOptionalASN1(&attrs, &hasAttrs, asn1.Tag(0).ContextSpecific().Constructed()) {
return nil, errors.New("malformed attributes")
}
if !hasAttrs {
return nil, nil
}
var contentType cryptobyte.String
var contentOID encasn1.ObjectIdentifier
for !attrs.Empty() {
if !attrs.ReadASN1(&contentType, asn1.SEQUENCE) {
return nil, errors.New("malformed content type")
}
if !contentType.ReadASN1ObjectIdentifier(&contentOID) {
return nil, errors.New("malformed content type oid")
}
if !contentType.ReadASN1(&contentType, asn1.SET) {
return nil, errors.New("content type set")
}
switch {
case contentOID.Equal(OIDAttributeMessageDigest):
var digest cryptobyte.String
if !contentType.ReadASN1(&digest, asn1.OCTET_STRING) {
return nil, errors.New("could not parse message digest")
}
attributes.MessageDigest = digest
case contentOID.Equal(OIDAttributeContentType):
var contentTypeOID encasn1.ObjectIdentifier
if !contentType.ReadASN1ObjectIdentifier(&contentTypeOID) {
return nil, errors.New("could not parse Content Type")
}
attributes.ContentType = contentTypeOID
case contentOID.Equal(OIDAttributeSigningTime):
if !contentType.ReadASN1UTCTime(&attributes.SigningTime) {
return nil, errors.New("could not parse Signing Time")
}
default:
// Save the bytes for any attributes we are not parsing.
attributes.Other = append(attributes.Other, &unparsedAttribute{
Type: contentOID,
Bytes: contentType,
})
}
}
return &attributes, nil
}
func parseEncryptedDigest(der *cryptobyte.String) ([]byte, error) {
var encryptedDigest cryptobyte.String
if !der.ReadASN1(&encryptedDigest, asn1.OCTET_STRING) {
return nil, errors.New("malfomed encrypted digest")
}
return encryptedDigest, nil
}
func parseSignerInfos(der *cryptobyte.String) (*signerinfo, error) {
var signerInfo cryptobyte.String
var si signerinfo
if !der.ReadASN1(&signerInfo, asn1.SEQUENCE) {
return nil, errors.New("no signer info")
}
var version int64
if !signerInfo.ReadASN1Integer(&version) {
return nil, errors.New("no version")
}
si.Version = version
ias, err := parseIssuerAndSerialNumber(&signerInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing issuer and serial number: %v", err)
}
si.IssuerAndSerialnumber = ias
//digestAlgo
algid, err := ParseAlgorithmIdentifier(&signerInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing digest algorithm: %v", err)
}
si.DigestAlgorithm = algid
//attributes
attrs, err := parseAttributes(&signerInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing attributes: %v", err)
}
si.AuthenticatedAttributes = attrs
// digest encrypted algorithm
algid, err = ParseAlgorithmIdentifier(&signerInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing encrypted digest algorithm: %v", err)
}
si.EncryptedDigestAlgorithm = algid
digest, err := parseEncryptedDigest(&signerInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing encrypted digest: %v", err)
}
si.EncryptedDigest = digest
return &si, nil
}
type signerinfo struct {
Version int64
EncryptedDigest []byte
DigestAlgorithm *pkix.AlgorithmIdentifier
AuthenticatedAttributes *Attributes
EncryptedDigestAlgorithm *pkix.AlgorithmIdentifier
IssuerAndSerialnumber *issuerAndSerialNumber
}
func (s *signerinfo) verify(cert *x509.Certificate) (bool, error) {
sigdata := s.AuthenticatedAttributes.Marshal()
err := cert.CheckSignature(x509.SHA256WithRSA, sigdata, s.EncryptedDigest)
if err != nil {
return false, err
}
return true, nil
}
func (s *signerinfo) isCertificate(cert *x509.Certificate) bool {
if !bytes.Equal(cert.RawIssuer, s.IssuerAndSerialnumber.RawIssuer) {
return false
}
if cert.SerialNumber.Cmp(s.IssuerAndSerialnumber.SerialNumber) != 0 {
return false
}
return true
}
type PKCS7 struct {
OID encasn1.ObjectIdentifier
SignerInfo []*signerinfo
ContentInfo []byte
Certs []*x509.Certificate
AlgorithmIdentifier *pkix.AlgorithmIdentifier
}
func (p *PKCS7) Verify(cert *x509.Certificate) (bool, error) {
for _, si := range p.SignerInfo {
if !si.isCertificate(cert) {
continue
}
ok, err := si.verify(cert)
if err != nil {
return false, fmt.Errorf("failed validating signature: %w", err)
}
if !ok {
continue
}
return true, nil
}
return false, nil
}
func (p *PKCS7) HasCertificate(cert *x509.Certificate) bool {
for _, si := range p.SignerInfo {
if si.isCertificate(cert) {
return true
}
}
return false
}
func ParsePKCS7(b []byte) (*PKCS7, error) {
var pkcs PKCS7
contentInfo := cryptobyte.String(b)
var oid encasn1.ObjectIdentifier
if ok, err := hasContentInfo(&contentInfo); ok {
oid, contentInfo, err = ParseContentInfo(&contentInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing contenting info: %v", err)
}
} else if err != nil {
return nil, fmt.Errorf("failed checking content info: %v", err)
}
pkcs.OID = oid
var signedData cryptobyte.String
if !contentInfo.ReadASN1(&signedData, asn1.SEQUENCE) {
return nil, errors.New("no signed data")
}
var version int64
if !signedData.ReadASN1Integer(&version) {
return nil, errors.New("no version")
}
var digest cryptobyte.String
if !signedData.ReadASN1(&digest, asn1.SET) {
return nil, errors.New("no digest crypto")
}
algid, err := ParseAlgorithmIdentifier(&digest)
if err != nil {
return nil, fmt.Errorf("failed algorithm identifier: %v", err)
}
pkcs.AlgorithmIdentifier = algid
oid, content, err := ParseContentInfo(&signedData)
if err != nil {
return nil, fmt.Errorf("failed parsing content info: %v", err)
}
pkcs.OID = oid
pkcs.ContentInfo = content
certs, err := parseCertificates(&signedData)
if err != nil {
return nil, fmt.Errorf("failed parsing certificates: %v", err)
}
pkcs.Certs = certs
var signerInfo cryptobyte.String
if !signedData.ReadASN1(&signerInfo, asn1.SET) {
return nil, errors.New("no signer info")
}
for !signerInfo.Empty() {
si, err := parseSignerInfos(&signerInfo)
if err != nil {
return nil, fmt.Errorf("failed parsing signer info: %v", err)
}
pkcs.SignerInfo = append(pkcs.SignerInfo, si)
}
return &pkcs, nil
}
type unparsedAttribute struct {
Type encasn1.ObjectIdentifier
Bytes []byte
}
type Attributes struct {
ContentType encasn1.ObjectIdentifier
MessageDigest []byte
SigningTime time.Time
Other []*unparsedAttribute
}
func (a *Attributes) Marshal() []byte {
b := cryptobyte.NewBuilder(nil)
// Attributes := SET OF Attribute
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
// Add the content type
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
b.AddASN1ObjectIdentifier(OIDAttributeContentType)
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
b.AddASN1ObjectIdentifier(a.ContentType)
})
})
if !a.SigningTime.IsZero() {
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
b.AddASN1ObjectIdentifier(OIDAttributeSigningTime)
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
b.AddASN1UTCTime(a.SigningTime)
})
})
}
// Digest from Authenticode
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
b.AddASN1ObjectIdentifier(OIDAttributeMessageDigest)
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
b.AddASN1OctetString(a.MessageDigest)
})
})
for _, attr := range a.Other {
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
b.AddASN1ObjectIdentifier(attr.Type)
b.AddASN1(asn1.SET, func(b *cryptobyte.Builder) {
b.AddBytes(attr.Bytes)
})
})
}
})
return b.BytesOrPanic()
}