-
Notifications
You must be signed in to change notification settings - Fork 8
/
sign.go
392 lines (333 loc) · 8.51 KB
/
sign.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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package sec
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"github.com/apache/mynewt-artifact/errors"
"golang.org/x/crypto/ed25519"
)
type SigType int
const (
SIG_TYPE_RSA2048 SigType = iota
SIG_TYPE_RSA3072
SIG_TYPE_ECDSA224
SIG_TYPE_ECDSA256
SIG_TYPE_ED25519
)
var sigTypeNameMap = map[SigType]string{
SIG_TYPE_RSA2048: "rsa2048",
SIG_TYPE_ECDSA224: "ecdsa224",
SIG_TYPE_ECDSA256: "ecdsa256",
SIG_TYPE_RSA3072: "rsa3072",
SIG_TYPE_ED25519: "ed25519",
}
type PrivSignKey struct {
// Only one of these members is non-nil.
Rsa *rsa.PrivateKey
Ec *ecdsa.PrivateKey
Ed25519 *ed25519.PrivateKey
}
type PubSignKey struct {
Rsa *rsa.PublicKey
Ec *ecdsa.PublicKey
Ed25519 ed25519.PublicKey
}
type Sig struct {
Type SigType
KeyHash []byte
Data []byte
}
var oidPrivateKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
func SigTypeString(typ SigType) string {
s := sigTypeNameMap[typ]
if s == "" {
return "unknown"
} else {
return s
}
}
func SigStringType(s string) (SigType, error) {
for k, v := range sigTypeNameMap {
if s == v {
return k, nil
}
}
return 0, errors.Errorf("unknown sig type name: \"%s\"", s)
}
func parsePrivSignKeyItf(keyBytes []byte) (interface{}, error) {
var privKey interface{}
var err error
block, data := pem.Decode(keyBytes)
if block != nil && block.Type == "EC PARAMETERS" {
/*
* Openssl prepends an EC PARAMETERS block before the
* key itself. If we see this first, just skip it,
* and go on to the data block.
*/
block, _ = pem.Decode(data)
}
if block != nil && block.Type == "RSA PRIVATE KEY" {
/*
* ParsePKCS1PrivateKey returns an RSA private key from its ASN.1
* PKCS#1 DER encoded form.
*/
privKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "Priv key parsing failed")
}
}
if block != nil && block.Type == "EC PRIVATE KEY" {
/*
* ParseECPrivateKey returns a EC private key
*/
privKey, err = x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "Priv key parsing failed")
}
}
if block != nil && block.Type == "PRIVATE KEY" {
// This indicates a PKCS#8 unencrypted private key.
// The particular type of key will be indicated within
// the key itself.
privKey, err = x509.ParsePKCS8PrivateKey(block.Bytes)
}
if block != nil && block.Type == "ENCRYPTED PRIVATE KEY" {
// This indicates a PKCS#8 key wrapped with PKCS#5
// encryption.
privKey, err = parseEncryptedPrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrapf(
err, "Unable to decode encrypted private key")
}
}
if privKey == nil {
return nil, errors.Errorf(
"Unknown private key format, EC/RSA private " +
"key in PEM format only.")
}
return privKey, nil
}
func ParsePubSignKey(keyBytes []byte) (PubSignKey, error) {
key := PubSignKey{}
itf, err := parsePubPemKey(keyBytes)
if err != nil {
return key, err
}
switch pub := itf.(type) {
case *rsa.PublicKey:
key.Rsa = pub
case *ecdsa.PublicKey:
key.Ec = pub
case ed25519.PublicKey:
key.Ed25519 = pub
default:
return key, errors.Errorf("unknown public signing key type: %T", pub)
}
return key, nil
}
func ParsePrivSignKey(keyBytes []byte) (PrivSignKey, error) {
key := PrivSignKey{}
itf, err := parsePrivSignKeyItf(keyBytes)
if err != nil {
return key, err
}
switch priv := itf.(type) {
case *rsa.PrivateKey:
key.Rsa = priv
case *ecdsa.PrivateKey:
key.Ec = priv
case ed25519.PrivateKey:
key.Ed25519 = &priv
default:
return key, errors.Errorf("unknown private key type: %T", itf)
}
return key, nil
}
func (key *PrivSignKey) AssertValid() {
if key.Rsa == nil && key.Ec == nil && key.Ed25519 == nil {
panic("invalid key; neither RSA nor ECC nor ED25519")
}
}
func (key *PrivSignKey) PubKey() PubSignKey {
key.AssertValid()
if key.Rsa != nil {
return PubSignKey{Rsa: &key.Rsa.PublicKey}
} else if key.Ec != nil {
return PubSignKey{Ec: &key.Ec.PublicKey}
} else {
x := PubSignKey{Ed25519: key.Ed25519.Public().(ed25519.PublicKey)}
return x
}
}
func (key *PrivSignKey) PubBytes() ([]byte, error) {
pk := key.PubKey()
return pk.Bytes()
}
func (key *PrivSignKey) SigLen() uint16 {
key.AssertValid()
if key.Rsa != nil {
pubk := key.Rsa.Public().(*rsa.PublicKey)
return uint16(pubk.Size())
} else if key.Ec != nil {
switch key.Ec.Curve.Params().Name {
case "P-224":
return 68
case "P-256":
return 72
default:
return 0
}
} else {
return ed25519.SignatureSize
}
}
func (key *PubSignKey) AssertValid() {
if key.Rsa == nil && key.Ec == nil && key.Ed25519 == nil {
panic("invalid public key; neither RSA nor ECC nor ED25519")
}
if key.Ed25519 != nil {
if _, err := marshalEd25519(key.Ed25519); err != nil {
panic("invalid public ed25519 key")
}
}
}
type pkixPublicKey struct {
Algo pkix.AlgorithmIdentifier
BitString asn1.BitString
}
func marshalEd25519(pubbytes []uint8) ([]uint8, error) {
pkix := pkixPublicKey{
Algo: pkix.AlgorithmIdentifier{
Algorithm: oidPrivateKeyEd25519,
},
BitString: asn1.BitString{
Bytes: pubbytes,
BitLength: 8 * len(pubbytes),
},
}
ret, err := asn1.Marshal(pkix)
if err != nil {
return nil, errors.Wrapf(err, "failed to encode ed25519 public key")
}
return ret, nil
}
func unmarshalEd25519(pubbytes []uint8) (pkixPublicKey, error) {
var pkix pkixPublicKey
if _, err := asn1.Unmarshal(pubbytes, &pkix); err != nil {
return pkix, errors.Wrapf(err, "failed to parse ed25519 public key")
}
return pkix, nil
}
func (key *PubSignKey) Bytes() ([]byte, error) {
key.AssertValid()
var b []byte
var err error
typ, err := key.SigType()
if err != nil {
return nil, err
}
switch typ {
case SIG_TYPE_RSA2048, SIG_TYPE_RSA3072:
b, err = asn1.Marshal(*key.Rsa)
case SIG_TYPE_ECDSA224, SIG_TYPE_ECDSA256:
b, err = x509.MarshalPKIXPublicKey(key.Ec)
case SIG_TYPE_ED25519:
b, err = marshalEd25519([]byte(key.Ed25519))
default:
err = errors.Errorf("unknown sig type: %v", typ)
}
if err != nil {
return nil, err
}
return b, nil
}
func (key *PubSignKey) SigType() (SigType, error) {
if key.Rsa != nil {
switch key.Rsa.Size() {
case 2048 / 8:
return SIG_TYPE_RSA2048, nil
case 3072 / 8:
return SIG_TYPE_RSA3072, nil
default:
return 0, errors.Errorf("unknown RSA key size (bytes): %d", key.Rsa.Size())
}
} else if key.Ec != nil {
switch key.Ec.Curve.Params().Name {
case "P-224":
return SIG_TYPE_ECDSA224, nil
case "P-256":
return SIG_TYPE_ECDSA256, nil
default:
return 0, errors.Errorf("unknown EC curve: %s", key.Ec.Curve.Params().Name)
}
} else if key.Ed25519 != nil {
return SIG_TYPE_ED25519, nil
}
return 0, errors.Errorf("invalid key: no non-nil members")
}
func (key *PubSignKey) Hash() ([]byte, error) {
pubBytes, err := key.Bytes()
if err != nil {
return nil, errors.WithStack(err)
}
return RawKeyHash(pubBytes), nil
}
func checkOneKeyOneSig(k PubSignKey, sig Sig, hash []byte) (bool, error) {
keyHash, err := k.Hash()
if err != nil {
return false, err
}
if !bytes.Equal(keyHash, sig.KeyHash) {
return false, nil
}
if k.Rsa != nil {
opts := rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
}
err := rsa.VerifyPSS(k.Rsa, crypto.SHA256, hash, sig.Data, &opts)
return err == nil, nil
}
if k.Ec != nil {
return false, errors.Errorf(
"ecdsa signature verification not supported")
}
if k.Ed25519 != nil {
return ed25519.Verify(k.Ed25519, hash, sig.Data), nil
}
return false, nil
}
func VerifySigs(key PubSignKey, sigs []Sig, hash []byte) (int, error) {
for i, s := range sigs {
match, err := checkOneKeyOneSig(key, s, hash)
if err != nil {
return -1, err
}
if match {
return i, nil
}
}
return -1, nil
}