-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathkeys.go
More file actions
539 lines (439 loc) · 12.1 KB
/
keys.go
File metadata and controls
539 lines (439 loc) · 12.1 KB
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
// keys.go -- Ed25519 keys management
//
// (c) 2016 Sudhi Herle <sudhi@herle.net>
//
// Licensing Terms: GPLv2
//
// If you need a commercial license for this work, please contact
// the author.
//
// This software does not come with any express or implied
// warranty; it is provided "as is". No claim is made to its
// suitability for any purpose.
// This file implements:
// - key generation, and key I/O
// - sign/verify of files and byte strings
package sigtool
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha3"
"crypto/sha512"
"crypto/subtle"
"encoding/pem"
"fmt"
"math/big"
"os"
"strings"
Ed "crypto/ed25519"
"golang.org/x/crypto/argon2"
"github.com/opencoff/sigtool/internal/pb"
)
// Private Ed25519 key
type PrivateKey struct {
sk []byte
// User provided comment string
Comment string
// Encryption key: Curve25519 point corresponding to this Ed25519 key
ck []byte
// Cached copy of the public key
pk *PublicKey
}
// Public Ed25519 key
type PublicKey struct {
pk []byte
// User provided comment string
Comment string
// Curve25519 point corresponding to this Ed25519 key
ck []byte
// fingerprint
fp []byte
}
// constants we use in this module
const (
_FpSize = 16 // Length of Ed25519 Public Key Hash
// Algorithm used in the encrypted private key
_Sk_algo = "sha3-argon2id"
// PEM Block header
_Sigtool_SK = "SIGTOOL PRIVATE KEY"
_Sigtool_PK = "SIGTOOL PUBLIC KEY"
// These are comforable margins exceeding
// NIST 2024 guidelines
_Argon2id_mem uint32 = 64 * 1024
_Argon2id_time uint32 = 2
_Argon2id_proc uint32 = 8
)
// given a public key, generate a deterministic short-hash of it.
func pkhash(pk []byte) []byte {
z := sha3.Sum256(pk)
return z[:_FpSize]
}
// NewPrivateKey generates a new Ed25519 private key
func NewPrivateKey(comment string) (*PrivateKey, error) {
pkb, skb, err := Ed.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
sk := &PrivateKey{
sk: []byte(skb),
Comment: comment,
pk: &PublicKey{
pk: []byte(pkb),
Comment: comment,
fp: pkhash([]byte(pkb)),
},
}
return sk, nil
}
// ParsePrivateKey makes a new private key from a previously serialized
// byte stream
func ParsePrivateKey(b []byte, getpw func() ([]byte, error)) (*PrivateKey, error) {
blk, _ := pem.Decode(b)
if blk == nil {
return nil, fmt.Errorf("sigtool: PrivateKey: No PEM")
}
if blk.Type == "OPENSSH PRIVATE KEY" {
return parseSSHPrivateKey(b, getpw)
}
if blk.Type != _Sigtool_SK {
return nil, fmt.Errorf("sigtool: PrivateKey: Not sigtool")
}
// validate the headers; without KDF and Algo, we're dead.
kdf, ok := blk.Headers["kdf"]
if !ok {
return nil, fmt.Errorf("sigtool: PrivateKey: Malformed PEM, no KDF")
}
_, a, err := parseKDF(kdf)
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey: %w", err)
}
// Unmarshal first
var ssk pb.Sk
if err := ssk.UnmarshalVT(blk.Bytes); err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey: %w", err)
}
var pw []byte
// we are now ready to decrypt
// but first get the user passphrase
if getpw != nil {
pwx, err := getpw()
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey: parse: %w", err)
}
pw = pwx
}
skb, err := skDecrypt(pw, &ssk, a)
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey: decrypt: %w", err)
}
// Now turn the raw bytes into a proper key
sk, err := makeSK(skb, blk.Headers["comment"])
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey: parse: %w", err)
}
return sk, nil
}
// ReadPrivateKey reads a file containing a private key. The private key
// can be an OpenSSH Private key (PEM) or a sigtool Private key (PEM).
func ReadPrivateKey(fn string, getpw func() ([]byte, error)) (*PrivateKey, error) {
skb, err := os.ReadFile(fn)
if err != nil {
return nil, fmt.Errorf("private key: %s: %w", fn, err)
}
sk, err := ParsePrivateKey(skb, getpw)
if err != nil {
return nil, fmt.Errorf("private key %s: %w", fn, err)
}
return sk, nil
}
// PublicKey returns the public key corresponding to this private key
func (sk *PrivateKey) PublicKey() *PublicKey {
return sk.pk
}
// Fingerprint returns the fingerprint of this key
// (A fingerprint is a truncated hash of the public key)
func (sk *PrivateKey) Fingerprint() string {
return sk.pk.Fingerprint()
}
// Equal returns true if the two PrivateKeys are equal and false otherwise
func (sk *PrivateKey) Equal(other *PrivateKey) bool {
return subtle.ConstantTimeCompare(sk.sk, other.sk) == 1
}
// ToCurve25519 converts an ed25519 private key to its corresponding
// curve25519 private key
func (sk *PrivateKey) ToCurve25519() []byte {
if sk.ck == nil {
var ek [64]byte
h := sha512.New()
h.Write(sk.sk[:32])
h.Sum(ek[:0])
sk.ck = clamp(ek[:32])
}
return sk.ck
}
// Marshal marshals the private key into sigtool native format by encrypting
// the private key with the user supplied function to get a passphrase
func (sk *PrivateKey) Marshal(getpw func() ([]byte, error)) ([]byte, error) {
var pw []byte
// first get the user passphrase
if getpw != nil {
pwx, err := getpw()
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey %s: marshal: %w", sk.Comment, err)
}
pw = pwx
}
// AES Encrypt the sk
esk, salt, err := sk.encrypt(pw)
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey %s: marshal: %w", sk.Comment, err)
}
kdf, err := encodeKDF(salt)
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey %s: marshal: %w", sk.Comment, err)
}
ssk := &pb.Sk{
Esk: esk,
}
skb, err := ssk.MarshalVT()
if err != nil {
return nil, fmt.Errorf("sigtool: PrivateKey %s: marshal: %w", sk.Comment, err)
}
// Put this in a PEM Block
blk := &pem.Block{
Type: _Sigtool_SK,
Headers: map[string]string{
"comment": sk.Comment,
"fingerprint": sk.pk.Fingerprint(),
"kdf": kdf,
},
Bytes: skb,
}
b := pem.EncodeToMemory(blk)
return b, nil
}
// encrypt the private key bytes with user supplied passphrase and using
// default argon2id params
func (sk *PrivateKey) encrypt(pw []byte) ([]byte, []byte, error) {
pwb := sha3.Sum512(pw)
salt := randBuf(32)
buf := argonKDF(_AEADNonceSize+_AesKeySize, pwb[:], salt)
key, nonce := buf[:_AesKeySize], buf[_AesKeySize:]
ciph, err := aes.NewCipher(key)
if err != nil {
return nil, nil, err
}
ae, err := cipher.NewGCM(ciph)
if err != nil {
return nil, nil, err
}
esk := ae.Seal(nil, nonce, sk.sk, nil)
return esk, salt, nil
}
// decrypt an encrypted Sk using the given user passphrase and KDF params
func skDecrypt(pw []byte, ssk *pb.Sk, a *pb.Argon) ([]byte, error) {
pwb := sha3.Sum512(pw)
buf := argon2.IDKey(pwb[:], a.Salt, a.Time,
a.Mem, uint8(0xff&a.Proc), uint32(_AEADNonceSize+_AesKeySize))
key, nonce := buf[:_AesKeySize], buf[_AesKeySize:]
ciph, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ae, err := cipher.NewGCM(ciph)
if err != nil {
return nil, err
}
skb, err := ae.Open(nil, nonce, ssk.Esk, nil)
if err != nil {
return nil, err
}
return skb, nil
}
// -- public key methods --
// ParsePublicKey makes a new public key from a previously serialized byte
// stream
func ParsePublicKey(b []byte) (*PublicKey, error) {
// We first try to parse this as a openssh public key string
if pk, err := parseEncPubKey(b, "cli-openssh-string"); err == nil {
return pk, nil
}
// Ok that didn't work; let's try to decode as openssh key
if pk, err := parseSSHPublicKey(b); err == nil {
return pk, nil
}
// Finally, try to decode as a sigtool key
blk, _ := pem.Decode(b)
if blk == nil {
return nil, fmt.Errorf("sigtool: PublicKey: No PEM")
}
if blk.Type != _Sigtool_PK {
return nil, fmt.Errorf("sigtool: PublicKey: Not sigtool")
}
// Unmarshal first
var spk pb.Pk
if err := spk.UnmarshalVT(blk.Bytes); err != nil {
return nil, fmt.Errorf("sigtool: PublicKey: %w", err)
}
pk, err := makePK(spk.Pk, blk.Headers["comment"])
if err != nil {
return nil, fmt.Errorf("sigtool: PublicKey: %w", err)
}
return pk, nil
}
// ReadPublicKey reads a public key from a file. The public key can be one of:
// - a string containing the openssh PK
// - a file containing the openssh PK
// - a file containing native sigtool PK
func ReadPublicKey(fn string) (*PublicKey, error) {
// first see if we can read the file
pkb, err := os.ReadFile(fn)
if err != nil {
// we couldn't; let's treat it as a string
pkb = []byte(fn)
}
// Now parse the public key
pk, err := ParsePublicKey(pkb)
if err != nil {
return nil, err
}
return pk, nil
}
// Fingerprint returns the fingerprint of this public key
func (pk *PublicKey) Fingerprint() string {
return tob64(pk.fp)
}
// Equal returns true if the two PrivateKeys are equal and false otherwise
func (pk *PublicKey) Equal(other *PublicKey) bool {
return subtle.ConstantTimeCompare(pk.pk, other.pk) == 1
}
// ToCurve25519 converts an Ed25519 Public Key to its corresponding Curve25519
// public key. This is directly from github.com/FiloSottile/age.
func (pk *PublicKey) ToCurve25519() []byte {
if pk.ck != nil {
return pk.ck
}
// ed25519.PublicKey is a little endian representation of the y-coordinate,
// with the most significant bit set based on the sign of the x-ccordinate.
bigEndianY := make([]byte, Ed.PublicKeySize)
for i, b := range pk.pk {
bigEndianY[Ed.PublicKeySize-i-1] = b
}
bigEndianY[0] &= 0b0111_1111
// The Montgomery u-coordinate is derived through the bilinear map
//
// u = (1 + y) / (1 - y)
//
// See https://blog.filippo.io/using-ed25519-keys-for-encryption.
y := new(big.Int).SetBytes(bigEndianY)
denom := big.NewInt(1)
denom.ModInverse(denom.Sub(denom, y), curve25519P) // 1 / (1 - y)
u := y.Mul(y.Add(y, big.NewInt(1)), denom)
u.Mod(u, curve25519P)
out := make([]byte, 32)
uBytes := u.Bytes()
n := len(uBytes)
for i, b := range uBytes {
out[n-i-1] = b
}
pk.ck = out
return out
}
// Marshal marshals the public key in sigtool native format
func (pk *PublicKey) Marshal() ([]byte, error) {
spk := &pb.Pk{
Pk: pk.pk,
}
pkb, err := spk.MarshalVT()
if err != nil {
return nil, fmt.Errorf("sigtool: PublicKey %s: marshal: %w", pk.Comment, err)
}
blk := &pem.Block{
Type: _Sigtool_PK,
Headers: map[string]string{
"comment": pk.Comment,
"fingerprint": pk.Fingerprint(),
},
Bytes: pkb,
}
b := pem.EncodeToMemory(blk)
return b, nil
}
// from github.com/FiloSottile/age
var curve25519P, _ = new(big.Int).SetString("57896044618658097711785492504343953926634992332820282019728792003956564819949", 10)
// -- Internal Utility Functions --
func makeSK(skb []byte, comm string) (*PrivateKey, error) {
if len(skb) != 64 {
return nil, fmt.Errorf("SK too small (%d)", len(skb))
}
edsk := Ed.PrivateKey(skb)
edpk := []byte(edsk.Public().(Ed.PublicKey))
pk := &PublicKey{
pk: edpk,
Comment: comm,
fp: pkhash(edpk),
}
sk := &PrivateKey{
sk: skb,
Comment: comm,
pk: pk,
}
return sk, nil
}
func makePK(pkb []byte, comm string) (*PublicKey, error) {
if len(pkb) != 32 {
return nil, fmt.Errorf("PK len wrong (%d)", len(pkb))
}
pk := &PublicKey{
pk: pkb,
Comment: comm,
fp: pkhash(pkb),
}
return pk, nil
}
func clamp(k []byte) []byte {
k[0] &= 248
k[31] &= 127
k[31] |= 64
return k
}
func argonKDF(n int, secret, salt []byte) []byte {
return argon2.IDKey(secret, salt, _Argon2id_time,
_Argon2id_mem, uint8(0xff&_Argon2id_proc), uint32(n))
}
func encodeKDF(salt []byte) (string, error) {
a := &pb.Argon{
Mem: _Argon2id_mem,
Time: _Argon2id_time,
Proc: _Argon2id_proc,
Salt: salt,
}
b, err := a.MarshalVT()
if err != nil {
return "", fmt.Errorf("kdf: marshal: %w", err)
}
s := fmt.Sprintf("%s:%s", _Sk_algo, tob64(b))
return s, nil
}
func parseKDF(s string) (string, *pb.Argon, error) {
i := strings.Index(s, ":")
if i < 0 {
return "", nil, fmt.Errorf("kdf: malformed string")
}
algo, s := s[:i], s[i+1:]
if algo != _Sk_algo {
return "", nil, fmt.Errorf("kdf: %s: unsupported algorithm", algo)
}
// now we have a b64url encoded protobuf.
b, err := fromb64(s)
if err != nil {
return "", nil, fmt.Errorf("kdf: malformed KDF params")
}
var a pb.Argon
if err = a.UnmarshalVT(b); err != nil {
return "", nil, fmt.Errorf("kdf: unmarshal: %w", err)
}
return algo, &a, nil
}
// vim: noexpandtab:ts=8:sw=8:tw=92: