-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathx509.go
386 lines (308 loc) · 8.73 KB
/
x509.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
package pkcs7
import (
"bytes"
"crypto/rsa"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"log"
"math/big"
"time"
"github.com/ddulesov/gogost/gost3410"
)
type unsignedData []byte
type signedData struct {
Version int `asn1:"default:1"`
DigestAlgorithmIdentifiers []pkix.AlgorithmIdentifier `asn1:"set"`
ContentInfo contentInfo
Certificates rawCertificates `asn1:"optional,tag:0"`
CRLs []pkix.CertificateList `asn1:"optional,tag:1"`
SignerInfos []signerInfo `asn1:"set"`
}
type rawCertificates struct {
Raw asn1.RawContent
}
type Certificate struct {
Raw asn1.RawContent
TBSCertificate tbsCertificate
SignatureAlgorithm pkix.AlgorithmIdentifier
SignatureValue asn1.BitString
}
// ParseCertificate parses a single certificate from the given ASN.1 DER data.
func ParseCertificate(asn1Data []byte) (*Certificate, error) {
var cert Certificate
rest, err := asn1.Unmarshal(asn1Data, &cert)
if err != nil {
return nil, err
}
if len(rest) > 0 {
return nil, asn1.SyntaxError{Msg: "trailing data"}
}
return &cert, nil
}
/*
func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
}
*/
// some GOST cryptographic function accept LE (little endian) Big integer as bytes array.
// golang big.Int internal representation is BE (big endian)
// Reverse convert LE to BE and vice versa
func Reverse(d []byte) {
for i, j := 0, len(d)-1; i < j; i, j = i+1, j-1 {
d[i], d[j] = d[j], d[i]
}
}
// RSA public key PKCS#1 representation
type pkcs1PublicKey struct {
N *big.Int
E int
}
// varifies signature over provided public key and digest/signature algorithm pair
// ToDo create and store PublicKey in certificate during parse state
// ToDo concern algorithm parameters for GOST cryptography . adjust PublicKey ParamSet according to them
func checkSignature(algo *SignatureAlgorithm, signed, signature []byte, pubKey []byte) error {
if algo == nil || !algo.hash.Actual() || !algo.pubKeyAlgo.Actual() {
return ErrUnsupportedAlgorithm
}
h := algo.hash.New()
h.Write(signed)
digest := h.Sum(nil)
switch algo.pubKeyAlgo {
case GOSTR3410_2001: // or GOSTR3410_2012_256
curve := gost3410.CurveIdGostR34102001CryptoProAParamSet()
pk, err := gost3410.NewPublicKey(curve, gost3410.Mode2001, pubKey)
if err != nil {
log.Print(err)
return ErrSignature
}
Reverse(digest)
ok, _ := pk.VerifyDigest(digest, signature[:])
if !ok {
return ErrSignature
}
/* GOSTR3410_2012_256 is the same as GOSTR3410_2001
case GOSTR3410_2012_256:
curve := gost3410.CurveIdGostR34102001CryptoProAParamSet()
pk, err := gost3410.NewPublicKey(curve, gost3410.Mode2001, pubKey)
if err != nil {
log.Print(err)
return ErrSignature
}
Reverse(digest)
ok, _ := pk.VerifyDigest(digest, signature[:])
if !ok {
log.Print("public key digest failed.")
return ErrSignature
}
*/
case GOSTR3410_2012_512:
curve := gost3410.CurveIdtc26gost341012512paramSetA()
pk, err := gost3410.NewPublicKey(curve, gost3410.Mode2012, pubKey)
if err != nil {
log.Print(err)
return ErrSignature
}
Reverse(digest)
ok, _ := pk.VerifyDigest(digest, signature[:])
if !ok {
return ErrSignature
}
case RSA:
//see. https://golang.org/src/crypto/x509/x509.go?s=27969:28036#L800
p := new(pkcs1PublicKey)
rest, err := asn1.Unmarshal(pubKey, p)
if err != nil {
log.Print(err)
return err
}
if len(rest) != 0 {
return errors.New("x509: trailing data after RSA public key")
}
pub := &rsa.PublicKey{
E: p.E,
N: p.N,
}
return rsa.VerifyPKCS1v15(pub, algo.hash.CryptoHash(), digest, signature)
default:
return ErrUnsupportedAlgorithm
}
return nil
}
// Verifies signature over certificate public key
func (c *Certificate) CheckSignature(algo *SignatureAlgorithm, signed, signature []byte) error {
var err error
var pubKey []byte
if algo == nil {
return ErrSignature
}
if algo.pubKeyAlgo == RSA {
pubKey = c.TBSCertificate.PublicKey.PublicKey.RightAlign()
} else {
var v asn1.RawValue
if _, err = asn1.Unmarshal(c.TBSCertificate.PublicKey.PublicKey.Bytes, &v); err != nil {
return err
}
pubKey = v.Bytes
}
return checkSignature(algo, signed, signature, pubKey)
}
// CheckSignatureFrom verifies that the signature on c is a valid signature
// from parent.
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
if parent == nil {
return nil
}
if bytes.Compare(c.TBSCertificate.Issuer.FullBytes, parent.TBSCertificate.Subject.FullBytes) != 0 {
return ErrSignature
}
/*
if (parent.Version == 3 && !parent.BasicConstraintsValid ||
parent.BasicConstraintsValid && !parent.IsCA) &&
!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
return ConstraintViolationError{}
}
if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
return ConstraintViolationError{}
}
if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
return ErrUnsupportedAlgorithm
}
*/
algo := GetSignatureAlgorithmForOid(c.TBSCertificate.SignatureAlgorithm.Algorithm)
if algo == nil {
log.Print("algo not fount", c.TBSCertificate.SignatureAlgorithm.Algorithm)
}
return parent.CheckSignature(algo, c.TBSCertificate.Raw, c.SignatureValue.RightAlign())
}
// asn.1 x509Certificate::tbsCertificate structure
// RFC5280
type tbsCertificate struct {
Raw asn1.RawContent
Version int `asn1:"optional,explicit,default:0,tag:0"`
SerialNumber *big.Int
SignatureAlgorithm pkix.AlgorithmIdentifier
Issuer asn1.RawValue
Validity validity
Subject asn1.RawValue
PublicKey publicKeyInfo
UniqueId asn1.BitString `asn1:"optional,tag:1"`
SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
}
type validity struct {
NotBefore, NotAfter time.Time
}
type GOSTCryptoProParameters struct {
ParamSet []asn1.ObjectIdentifier
}
// asn.1 Certificate PublicKey structure
// RFC5280
type publicKeyInfo struct {
//Raw asn1.RawContent
Algorithm pkix.AlgorithmIdentifier
PublicKey asn1.BitString
}
// asn.1 CMS Attribute
// RFC5652
type attribute struct {
Type asn1.ObjectIdentifier
Value asn1.RawValue `asn1:"set"`
}
// asn.1 Signature issuer
type issuerAndSerial struct {
IssuerName asn1.RawValue
SerialNumber *big.Int
}
type signedAttrs struct {
Raw asn1.RawContent
}
// asn.1 CMS SignerInfo struct
// RFC5652
type signerInfo struct {
Version int `asn1:"default:1"`
IssuerAndSerialNumber issuerAndSerial
DigestAlgorithm pkix.AlgorithmIdentifier
AuthenticatedAttributes signedAttrs `asn1:"optional,tag:0"`
DigestEncryptionAlgorithm pkix.AlgorithmIdentifier
EncryptedDigest []byte
UnauthenticatedAttributes []attribute `asn1:"optional,tag:1"`
}
// Parse parses a single certificate from the given asn.1 DER data.
func (raw rawCertificates) Parse() ([]*Certificate, error) {
var v []*Certificate
if len(raw.Raw) == 0 {
return nil, nil
}
var val asn1.RawValue
if _, err := asn1.Unmarshal(raw.Raw, &val); err != nil {
return nil, err
}
asn1Data := val.Bytes
for len(asn1Data) > 0 {
cert := new(Certificate)
var err error
asn1Data, err = asn1.Unmarshal(asn1Data, cert)
if err != nil {
return nil, err
}
v = append(v, cert)
}
return v, nil
//return x509.ParseCertificates(val.Bytes)
}
/*
type SignedData struct {
sd signedData
certs []*x509.Certificate
messageDigest []byte
}
*/
// asn.1 CMS::SignerInfo
// RFC5652
type Attribute struct {
Type asn1.ObjectIdentifier
Value interface{}
}
/*
type SignerInfoConfig struct {
ExtraSignedAttributes []Attribute
}
*/
// asn.1 CMS representation
// RFC5652
type contentInfo struct {
ContentType asn1.ObjectIdentifier
Content asn1.RawValue `asn1:"explicit,optional,tag:0"`
}
func parseSignedData(data []byte) (*CMS, error) {
var sd signedData
asn1.Unmarshal(data, &sd)
certs, err := sd.Certificates.Parse()
if err != nil {
return nil, err
}
// fmt.Printf("--> Signed Data Version %d\n", sd.Version)
var compound asn1.RawValue
var content unsignedData
// The Content.Bytes maybe empty on PKI responses.
if len(sd.ContentInfo.Content.Bytes) > 0 {
if _, err := asn1.Unmarshal(sd.ContentInfo.Content.Bytes, &compound); err != nil {
return nil, err
}
}
// Compound octet string
if compound.IsCompound {
if _, err = asn1.Unmarshal(compound.Bytes, &content); err != nil {
return nil, err
}
} else {
// assuming this is tag 04
content = compound.Bytes
}
return &CMS{
Content: content,
Certificates: certs,
CRLs: sd.CRLs,
Signers: sd.SignerInfos,
raw: sd}, nil
}