-
Notifications
You must be signed in to change notification settings - Fork 255
/
validator.go
442 lines (357 loc) · 11.9 KB
/
validator.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
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package secp256r1
import (
"bytes"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"math/big"
"reflect"
"time"
"github.com/33cn/chain33/system/crypto/common/authority/core"
"github.com/33cn/chain33/system/crypto/common/authority/utils"
"crypto/ecdsa"
log "github.com/33cn/chain33/common/log/log15"
)
var authLogger = log.New("module", "crypto")
type ecdsaValidator struct {
rootCerts []*x509.Certificate
intermediateCerts []*x509.Certificate
certificationTreeInternalNodesMap map[string]bool
opts *x509.VerifyOptions
CRL []*pkix.CertificateList
}
// NewEcdsaValidator 创建ecdsa校验器
func NewEcdsaValidator() core.Validator {
return &ecdsaValidator{}
}
func (validator *ecdsaValidator) getCertFromPem(idBytes []byte) (*x509.Certificate, error) {
if idBytes == nil {
return nil, fmt.Errorf("getIdentityFromConf error: nil idBytes")
}
pemCert, _ := pem.Decode(idBytes)
if pemCert == nil {
return nil, fmt.Errorf("getIdentityFromBytes error: could not decode pem bytes [%v]", idBytes)
}
var cert *x509.Certificate
cert, err := x509.ParseCertificate(pemCert.Bytes)
if err != nil {
return nil, fmt.Errorf("getIdentityFromBytes error: failed to parse x509 cert, err %s", err)
}
return cert, nil
}
func getSubjectKeyIdentifierFromCert(cert *x509.Certificate) ([]byte, error) {
var SKI []byte
for _, ext := range cert.Extensions {
if reflect.DeepEqual(ext.Id, asn1.ObjectIdentifier{2, 5, 29, 14}) {
_, err := asn1.Unmarshal(ext.Value, &SKI)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal Subject Key Identifier, err %s", err)
}
return SKI, nil
}
}
return nil, errors.New("subjectKeyIdentifier not found in certificate")
}
func isCACert(cert *x509.Certificate) bool {
_, err := getSubjectKeyIdentifierFromCert(cert)
if err != nil {
return false
}
if !cert.IsCA {
return false
}
return true
}
func (validator *ecdsaValidator) Setup(conf *core.AuthConfig) error {
if conf == nil {
return fmt.Errorf("Setup error: nil conf reference")
}
if err := validator.setupCAs(conf); err != nil {
return err
}
if err := validator.setupCRLs(conf); err != nil {
return err
}
if err := validator.finalizeSetupCAs(conf); err != nil {
return err
}
return nil
}
func (validator *ecdsaValidator) Validate(certByte []byte, pubKey []byte) error {
authLogger.Debug("validating certificate")
cert, err := validator.getCertFromPem(certByte)
if err != nil {
return fmt.Errorf("ParseCertificate failed %s", err)
}
certPubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
if !ok {
return fmt.Errorf("Error publick key type in transaction. expect ECDSA")
}
if !bytes.Equal(pubKey, SerializePublicKeyCompressed(certPubKey)) {
return fmt.Errorf("Invalid public key")
}
cert, err = validator.sanitizeCert(cert)
if err != nil {
return fmt.Errorf("Sanitize certification failed. err %s", err)
}
validationChain, err := validator.getCertificationChain(cert)
if err != nil {
return fmt.Errorf("Could not obtain certification chain, err %s", err)
}
err = validator.validateCertAgainstChain(cert.SerialNumber, validationChain)
if err != nil {
return fmt.Errorf("Could not validate identity against certification chain, err %s", err)
}
return nil
}
func (validator *ecdsaValidator) getCertificationChain(cert *x509.Certificate) ([]*x509.Certificate, error) {
if validator.opts == nil {
return nil, errors.New("Invalid validator instance")
}
if cert.IsCA {
return nil, errors.New("A CA certificate cannot be used directly")
}
return validator.getValidationChain(cert, false)
}
func (validator *ecdsaValidator) getUniqueValidationChain(cert *x509.Certificate, opts x509.VerifyOptions) ([]*x509.Certificate, error) {
if validator.opts == nil {
return nil, fmt.Errorf("The supplied identity has no verify options")
}
validationChains, err := cert.Verify(opts)
if err != nil {
return nil, fmt.Errorf("The supplied identity is not valid, Verify() returned %s", err)
}
if len(validationChains) != 1 {
return nil, fmt.Errorf("Only supports a single validation chain, got %d", len(validationChains))
}
return validationChains[0], nil
}
func (validator *ecdsaValidator) getValidationChain(cert *x509.Certificate, isIntermediateChain bool) ([]*x509.Certificate, error) {
validationChain, err := validator.getUniqueValidationChain(cert, validator.getValidityOptsForCert(cert))
if err != nil {
return nil, fmt.Errorf("Failed getting validation chain %s", err)
}
if len(validationChain) < 2 {
return nil, fmt.Errorf("Expected a chain of length at least 2, got %d", len(validationChain))
}
parentPosition := 1
if isIntermediateChain {
parentPosition = 0
}
if validator.certificationTreeInternalNodesMap[string(validationChain[parentPosition].Raw)] {
return nil, fmt.Errorf("Invalid validation chain. Parent certificate should be a leaf of the certification tree [%v]", cert.Raw)
}
return validationChain, nil
}
func (validator *ecdsaValidator) setupCAs(conf *core.AuthConfig) error {
if len(conf.RootCerts) == 0 {
return errors.New("Expected at least one CA certificate")
}
validator.opts = &x509.VerifyOptions{Roots: x509.NewCertPool(), Intermediates: x509.NewCertPool()}
for _, v := range conf.RootCerts {
cert, err := validator.getCertFromPem(v)
if err != nil {
return err
}
validator.opts.Roots.AddCert(cert)
}
for _, v := range conf.IntermediateCerts {
cert, err := validator.getCertFromPem(v)
if err != nil {
return err
}
validator.opts.Intermediates.AddCert(cert)
}
validator.rootCerts = make([]*x509.Certificate, len(conf.RootCerts))
for i, trustedCert := range conf.RootCerts {
cert, err := validator.getCertFromPem(trustedCert)
if err != nil {
return err
}
cert, err = validator.sanitizeCert(cert)
if err != nil {
return err
}
validator.rootCerts[i] = cert
}
validator.intermediateCerts = make([]*x509.Certificate, len(conf.IntermediateCerts))
for i, trustedCert := range conf.IntermediateCerts {
cert, err := validator.getCertFromPem(trustedCert)
if err != nil {
return err
}
cert, err = validator.sanitizeCert(cert)
if err != nil {
return err
}
validator.intermediateCerts[i] = cert
}
validator.opts = &x509.VerifyOptions{Roots: x509.NewCertPool(), Intermediates: x509.NewCertPool()}
for _, cert := range validator.rootCerts {
validator.opts.Roots.AddCert(cert)
}
for _, cert := range validator.intermediateCerts {
validator.opts.Intermediates.AddCert(cert)
}
return nil
}
func (validator *ecdsaValidator) setupCRLs(conf *core.AuthConfig) error {
validator.CRL = make([]*pkix.CertificateList, len(conf.RevocationList))
for i, crlbytes := range conf.RevocationList {
crl, err := x509.ParseCRL(crlbytes)
if err != nil {
return fmt.Errorf("Could not parse RevocationList, err %s", err)
}
validator.CRL[i] = crl
}
return nil
}
func (validator *ecdsaValidator) finalizeSetupCAs(config *core.AuthConfig) error {
for _, cert := range append(append([]*x509.Certificate{}, validator.rootCerts...), validator.intermediateCerts...) {
if !isCACert(cert) {
return fmt.Errorf("CA Certificate did not have the Subject Key Identifier extension, (SN: %s)", cert.SerialNumber)
}
if err := validator.validateCAIdentity(cert); err != nil {
return fmt.Errorf("CA Certificate is not valid, (SN: %s) [%s]", cert.SerialNumber, err)
}
}
validator.certificationTreeInternalNodesMap = make(map[string]bool)
for _, cert := range append([]*x509.Certificate{}, validator.intermediateCerts...) {
chain, err := validator.getUniqueValidationChain(cert, validator.getValidityOptsForCert(cert))
if err != nil {
return fmt.Errorf("Failed getting validation chain, (SN: %s)", cert.SerialNumber)
}
for i := 1; i < len(chain); i++ {
validator.certificationTreeInternalNodesMap[string(chain[i].Raw)] = true
}
}
return nil
}
func (validator *ecdsaValidator) sanitizeCert(cert *x509.Certificate) (*x509.Certificate, error) {
if core.IsECDSASignedCert(cert) {
var parentCert *x509.Certificate
if cert.IsCA {
chain, err := validator.getUniqueValidationChain(cert, validator.getValidityOptsForCert(cert))
if err != nil {
return nil, err
}
if len(chain) == 1 {
parentCert = cert
} else {
parentCert = chain[1]
}
} else {
chain, err := validator.getUniqueValidationChain(cert, validator.getValidityOptsForCert(cert))
if err != nil {
return nil, err
}
parentCert = chain[1]
}
var err error
cert, err = sanitizeECDSASignedCert(cert, parentCert)
if err != nil {
return nil, err
}
}
return cert, nil
}
func (validator *ecdsaValidator) validateCAIdentity(cert *x509.Certificate) error {
if !cert.IsCA {
return errors.New("Only CA identities can be validated")
}
validationChain, err := validator.getUniqueValidationChain(cert, validator.getValidityOptsForCert(cert))
if err != nil {
return fmt.Errorf("Could not obtain certification chain, err %s", err)
}
if len(validationChain) == 1 {
return nil
}
return validator.validateCertAgainstChain(cert.SerialNumber, validationChain)
}
func (validator *ecdsaValidator) validateCertAgainstChain(serialNumber *big.Int, validationChain []*x509.Certificate) error {
SKI, err := getSubjectKeyIdentifierFromCert(validationChain[1])
if err != nil {
return fmt.Errorf("Could not obtain Subject Key Identifier for signer cert, err %s", err)
}
for _, crl := range validator.CRL {
aki, err := core.GetAuthorityKeyIdentifierFromCrl(crl)
if err != nil {
return fmt.Errorf("Could not obtain Authority Key Identifier for crl, err %s", err)
}
if bytes.Equal(aki, SKI) {
for _, rc := range crl.TBSCertList.RevokedCertificates {
if rc.SerialNumber.Cmp(serialNumber) == 0 {
err = validationChain[1].CheckCRLSignature(crl)
if err != nil {
authLogger.Warn("Invalid signature over the identified CRL, error %s", err)
continue
}
return errors.New("The certificate has been revoked")
}
}
}
}
return nil
}
func (validator *ecdsaValidator) getValidityOptsForCert(cert *x509.Certificate) x509.VerifyOptions {
var tempOpts x509.VerifyOptions
tempOpts.Roots = validator.opts.Roots
tempOpts.DNSName = validator.opts.DNSName
tempOpts.Intermediates = validator.opts.Intermediates
tempOpts.KeyUsages = validator.opts.KeyUsages
tempOpts.CurrentTime = cert.NotBefore.Add(time.Second)
return tempOpts
}
func (validator *ecdsaValidator) GetCertFromSignature(signature []byte) ([]byte, error) {
certSign, err := utils.DecodeCertFromSignature(signature)
if err != nil {
authLogger.Error(fmt.Sprintf("unmashal certificate from signature failed. %s", err.Error()))
return nil, err
}
if len(certSign.Cert) == 0 {
authLogger.Error("cert can not be null")
return nil, errors.New("ErrInvalidParam")
}
return certSign.Cert, nil
}
func sanitizeECDSASignedCert(cert *x509.Certificate, parentCert *x509.Certificate) (*x509.Certificate, error) {
if cert == nil {
return nil, errors.New("Certificate must be different from nil")
}
if parentCert == nil {
return nil, errors.New("Parent certificate must be different from nil")
}
expectedSig, err := signatureToLowS(parentCert.PublicKey.(*ecdsa.PublicKey), cert.Signature)
if err != nil {
return nil, err
}
if bytes.Equal(cert.Signature, expectedSig) {
return cert, nil
}
var newCert core.Certificate
newCert, err = core.CertFromX509Cert(cert)
if err != nil {
return nil, err
}
newCert.SignatureValue = asn1.BitString{Bytes: expectedSig, BitLength: len(expectedSig) * 8}
newCert.Raw = nil
newRaw, err := asn1.Marshal(newCert)
if err != nil {
return nil, err
}
return x509.ParseCertificate(newRaw)
}
func signatureToLowS(k *ecdsa.PublicKey, signature []byte) ([]byte, error) {
r, s, err := UnmarshalECDSASignature(signature)
if err != nil {
return nil, err
}
s = ToLowS(k, s)
return MarshalECDSASignature(r, s)
}