-
Notifications
You must be signed in to change notification settings - Fork 0
/
keygen.txt
536 lines (459 loc) · 12.5 KB
/
keygen.txt
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
// Package keygen handles the creation of new SSH key pairs.
package keygen
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"encoding/pem"
"errors"
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"golang.org/x/crypto/ssh"
)
// KeyType represents a type of SSH key.
type KeyType string
// Supported key types.
const (
RSA KeyType = "rsa"
Ed25519 KeyType = "ed25519"
ECDSA KeyType = "ecdsa"
)
// String implements the Stringer interface for KeyType.
func (k KeyType) String() string {
return string(k)
}
const rsaDefaultBits = 4096
// ErrMissingSSHKeys indicates we're missing some keys that we expected to
// have after generating. This should be an extreme edge case.
var ErrMissingSSHKeys = errors.New("missing one or more keys; did something happen to them after they were generated?")
// ErrUnsupportedKeyType indicates an unsupported key type.
type ErrUnsupportedKeyType struct {
keyType string
ecName string
}
// Error implements the error interface for ErrUnsupportedKeyType.
func (e ErrUnsupportedKeyType) Error() string {
err := "unsupported key type"
if e.keyType != "" {
err += fmt.Sprintf(": %s", e.keyType)
}
if e.ecName != "" {
err += fmt.Sprintf(" (ECDSA curve: %s)", e.ecName)
}
return err
}
// FilesystemErr is used to signal there was a problem creating keys at the
// filesystem-level. For example, when we're unable to create a directory to
// store new SSH keys in.
type FilesystemErr struct {
Err error
}
// Error returns a human-readable string for the error. It implements the error
// interface.
func (e FilesystemErr) Error() string {
return e.Err.Error()
}
// Unwrap returns the underlying error.
func (e FilesystemErr) Unwrap() error {
return e.Err
}
// SSHKeysAlreadyExistErr indicates that files already exist at the location at
// which we're attempting to create SSH keys.
type SSHKeysAlreadyExistErr struct {
Path string
}
// SSHKeyPair holds a pair of SSH keys and associated methods.
// Deprecated: Use KeyPair instead.
type SSHKeyPair = KeyPair
// KeyPair holds a pair of SSH keys and associated methods.
type KeyPair struct {
path string // private key filename path; public key will have .pub appended
writeKeys bool
passphrase []byte
rsaBitSize int
ec elliptic.Curve
keyType KeyType
privateKey crypto.PrivateKey
}
func (s KeyPair) privateKeyPath() string {
return s.path
}
func (s KeyPair) publicKeyPath() string {
return s.privateKeyPath() + ".pub"
}
// Option is a functional option for KeyPair.
type Option func(*KeyPair)
// WithPassphrase sets the passphrase for the private key.
func WithPassphrase(passphrase string) Option {
return func(s *KeyPair) {
s.passphrase = []byte(passphrase)
}
}
// WithKeyType sets the key type for the key pair.
// Available key types are RSA, Ed25519, and ECDSA.
func WithKeyType(keyType KeyType) Option {
return func(s *KeyPair) {
s.keyType = keyType
}
}
// WithBitSize sets the key size for the RSA key pair.
// This option is ignored for other key types.
func WithBitSize(bits int) Option {
return func(s *KeyPair) {
s.rsaBitSize = bits
}
}
// WithWrite writes the key pair to disk if it doesn't exist.
func WithWrite() Option {
return func(s *KeyPair) {
s.writeKeys = true
}
}
// WithEllipticCurve sets the elliptic curve for the ECDSA key pair.
// Supported curves are P-256, P-384, and P-521.
// The default curve is P-384.
// This option is ignored for other key types.
func WithEllipticCurve(curve elliptic.Curve) Option {
return func(s *KeyPair) {
s.ec = curve
}
}
// New generates a KeyPair, which contains a pair of SSH keys.
//
// If the key pair already exists, it will be loaded from disk, otherwise, a
// new SSH key pair is generated.
// If no key type is specified, Ed25519 will be used.
func New(path string, opts ...Option) (*KeyPair, error) {
var err error
s := &KeyPair{
path: expandPath(path),
rsaBitSize: rsaDefaultBits,
ec: elliptic.P384(),
keyType: Ed25519,
}
for _, opt := range opts {
opt(s)
}
ecName := s.ec.Params().Name
switch ecName {
case "P-256", "P-384", "P-521":
default:
return nil, ErrUnsupportedKeyType{keyType: ecName, ecName: ecName}
}
if s.KeyPairExists() {
privData, err := os.ReadFile(s.privateKeyPath())
if err != nil {
return nil, err
}
var k interface{}
if len(s.passphrase) > 0 {
k, err = ssh.ParseRawPrivateKeyWithPassphrase(privData, s.passphrase)
} else {
k, err = ssh.ParseRawPrivateKey(privData)
}
if err != nil {
return nil, err
}
switch k := k.(type) {
case *rsa.PrivateKey:
s.keyType = RSA
s.privateKey = k
case *ecdsa.PrivateKey:
s.keyType = ECDSA
s.privateKey = k
case *ed25519.PrivateKey:
s.keyType = Ed25519
s.privateKey = k
default:
return nil, ErrUnsupportedKeyType{keyType: fmt.Sprintf("%T", k)}
}
return s, nil
}
switch s.keyType {
case Ed25519:
err = s.generateEd25519Keys()
case RSA:
err = s.generateRSAKeys(s.rsaBitSize)
case ECDSA:
err = s.generateECDSAKeys(s.ec)
default:
return nil, ErrUnsupportedKeyType{keyType: string(s.keyType)}
}
if err != nil {
return nil, err
}
if s.writeKeys {
return s, s.WriteKeys()
}
return s, nil
}
// PrivateKey returns the unencrypted crypto.PrivateKey.
func (s *KeyPair) PrivateKey() crypto.PrivateKey {
switch s.keyType {
case RSA, Ed25519, ECDSA:
return s.privateKey
default:
return nil
}
}
// Ensure that KeyPair implements crypto.Signer.
// This is used to ensure that the private key is a valid crypto.Signer to be
// passed to ssh.NewSignerFromKey.
var (
_ crypto.Signer = (*rsa.PrivateKey)(nil)
_ crypto.Signer = (*ecdsa.PrivateKey)(nil)
_ crypto.Signer = (*ed25519.PrivateKey)(nil)
)
// Signer returns an ssh.Signer for the key pair.
func (s *KeyPair) Signer() ssh.Signer {
sk, _ := ssh.NewSignerFromKey(s.PrivateKey())
return sk
}
// PublicKey returns the ssh.PublicKey for the key pair.
func (s *KeyPair) PublicKey() ssh.PublicKey {
p, _ := ssh.NewPublicKey(s.cryptoPublicKey())
return p
}
func (s *KeyPair) cryptoPublicKey() crypto.PublicKey {
switch s.keyType {
case RSA:
key, ok := s.privateKey.(*rsa.PrivateKey)
if !ok {
return nil
}
return key.Public()
case Ed25519:
key, ok := s.privateKey.(*ed25519.PrivateKey)
if !ok {
return nil
}
return key.Public()
case ECDSA:
key, ok := s.privateKey.(*ecdsa.PrivateKey)
if !ok {
return nil
}
return key.Public()
default:
return nil
}
}
// CryptoPublicKey returns the crypto.PublicKey of the SSH key pair.
func (s *KeyPair) CryptoPublicKey() crypto.PublicKey {
return s.cryptoPublicKey()
}
// RawAuthorizedKey returns the underlying SSH public key (RFC 4253) in OpenSSH
// authorized_keys format.
func (s *KeyPair) RawAuthorizedKey() []byte {
bts, err := os.ReadFile(s.publicKeyPath())
if err != nil {
return []byte(s.AuthorizedKey())
}
_, c, opts, _, err := ssh.ParseAuthorizedKey(bts)
if err != nil {
return []byte(s.AuthorizedKey())
}
ak := s.authorizedKey(s.PublicKey())
if len(opts) > 0 {
ak = fmt.Sprintf("%s %s", strings.Join(opts, ","), ak)
}
if c != "" {
ak = fmt.Sprintf("%s %s", ak, c)
}
return []byte(ak)
}
func (s *KeyPair) authorizedKey(pk ssh.PublicKey) string {
if pk == nil {
return ""
}
// serialize authorized key
return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pk)))
}
// AuthorizedKey returns the SSH public key (RFC 4253) in OpenSSH authorized_keys
// format. The returned string is trimmed of sshd options and comments.
func (s *KeyPair) AuthorizedKey() string {
return s.authorizedKey(s.PublicKey())
}
// RawPrivateKey returns the raw unencrypted private key bytes in PEM format.
func (s *KeyPair) RawPrivateKey() []byte {
return s.rawPrivateKey(nil)
}
// RawProtectedPrivateKey returns the raw password protected private key bytes
// in PEM format.
func (s *KeyPair) RawProtectedPrivateKey() []byte {
return s.rawPrivateKey(s.passphrase)
}
func (s *KeyPair) rawPrivateKey(pass []byte) []byte {
block, err := s.pemBlock(pass)
if err != nil {
return nil
}
return pem.EncodeToMemory(block)
}
func (s *KeyPair) pemBlock(passphrase []byte) (*pem.Block, error) {
key := s.PrivateKey()
if key == nil {
return nil, ErrMissingSSHKeys
}
switch s.keyType {
case RSA, Ed25519, ECDSA:
if len(passphrase) > 0 {
return ssh.MarshalPrivateKeyWithPassphrase(key, "", passphrase)
}
return ssh.MarshalPrivateKey(key, "")
default:
return nil, ErrUnsupportedKeyType{keyType: s.keyType.String()}
}
}
// generateEd25519Keys creates a pair of EdD25519 keys for SSH auth.
func (s *KeyPair) generateEd25519Keys() error {
// Generate keys
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return err
}
s.privateKey = &privateKey
return nil
}
// generateEd25519Keys creates a pair of EdD25519 keys for SSH auth.
func (s *KeyPair) generateECDSAKeys(curve elliptic.Curve) error {
// Generate keys
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return err
}
s.privateKey = privateKey
return nil
}
// generateRSAKeys creates a pair for RSA keys for SSH auth.
func (s *KeyPair) generateRSAKeys(bitSize int) error {
// Generate private key
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return err
}
// Validate private key
err = privateKey.Validate()
if err != nil {
return err
}
s.privateKey = privateKey
return nil
}
// prepFilesystem makes sure the state of the filesystem is as it needs to be
// in order to write our keys to disk. It will create and/or set permissions on
// the SSH directory we're going to write our keys to (for example, ~/.ssh) as
// well as make sure that no files exist at the location in which we're going
// to write out keys.
func (s *KeyPair) prepFilesystem() error {
var err error
keyDir := filepath.Dir(s.path)
if keyDir != "" {
keyDir, err = filepath.Abs(keyDir)
if err != nil {
return err
}
info, err := os.Stat(keyDir)
if os.IsNotExist(err) {
// Directory doesn't exist: create it
return os.MkdirAll(keyDir, 0o700)
}
if err != nil {
// There was another error statting the directory; something is awry
return FilesystemErr{Err: err}
}
if !info.IsDir() {
// It exists but it's not a directory
return FilesystemErr{Err: fmt.Errorf("%s is not a directory", keyDir)}
}
if info.Mode().Perm() != 0o700 {
// Permissions are wrong: fix 'em
if err := os.Chmod(keyDir, 0o700); err != nil {
return FilesystemErr{Err: err}
}
}
}
// Make sure the files we're going to write to don't already exist
if fileExists(s.privateKeyPath()) {
return SSHKeysAlreadyExistErr{Path: s.privateKeyPath()}
}
if fileExists(s.publicKeyPath()) {
return SSHKeysAlreadyExistErr{Path: s.publicKeyPath()}
}
// The directory looks good as-is
return nil
}
// WriteKeys writes the SSH key pair to disk.
func (s *KeyPair) WriteKeys() error {
var err error
priv := s.RawProtectedPrivateKey()
if priv == nil {
return ErrMissingSSHKeys
}
if err = s.prepFilesystem(); err != nil {
return err
}
if err := writeKeyToFile(priv, s.privateKeyPath()); err != nil {
return err
}
ak := s.AuthorizedKey()
if memo := pubKeyMemo(); memo != "" {
ak = fmt.Sprintf("%s %s", ak, memo)
}
return writeKeyToFile([]byte(ak), s.publicKeyPath())
}
// KeyPairExists checks if the SSH key pair exists on disk.
func (s *KeyPair) KeyPairExists() bool {
return fileExists(s.privateKeyPath())
}
func writeKeyToFile(keyBytes []byte, path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
return os.WriteFile(path, keyBytes, 0o600)
}
return FilesystemErr{Err: fmt.Errorf("file %s already exists", path)}
}
func fileExists(path string) bool {
_, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
if err != nil {
return false
}
return true
}
// expandPath resolves the tilde `~` and any environment variables in path.
func expandPath(path string) string {
if len(path) > 0 && path[0] == '~' {
userdir, err := os.UserHomeDir()
if err != nil {
return path
}
path = filepath.Join(userdir, path[1:])
}
return os.ExpandEnv(path)
}
// attaches a user@host suffix to a serialized public key. returns the original
// pubkey if we can't get the username or host.
func pubKeyMemo() string {
u, err := user.Current()
if err != nil {
return ""
}
hostname, err := os.Hostname()
if err != nil {
return ""
}
return fmt.Sprintf("%s@%s\n", u.Username, hostname)
}
// Error returns the a human-readable error message for SSHKeysAlreadyExistErr.
// It satisfies the error interface.
func (e SSHKeysAlreadyExistErr) Error() string {
return fmt.Sprintf("ssh key %s already exists", e.Path)
}