-
Notifications
You must be signed in to change notification settings - Fork 5
/
ssh.go
82 lines (67 loc) · 1.9 KB
/
ssh.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
package gitdb
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"os"
"github.com/bouggo/log"
"golang.org/x/crypto/ssh"
)
// generateSSHKeyPair make a pair of public and private keys for SSH access.
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
// Private Key generated is PEM encoded
func (g *gitdb) generateSSHKeyPair() error {
if _, err := os.Stat(g.privateKeyFilePath()); err == nil {
if _, err := os.Stat(g.publicKeyFilePath()); err == nil {
return nil
}
log.Info("Re-generating public key")
//public key is missing - recreate public key
pkPem, err := ioutil.ReadFile(g.privateKeyFilePath())
if err != nil {
return err
}
b, _ := pem.Decode(pkPem)
privateKey, err := x509.ParsePKCS1PrivateKey(b.Bytes)
if err != nil {
return err
}
return g.generatePublicKey(privateKey)
}
if err := os.MkdirAll(g.sshDir(), os.ModePerm); err != nil {
return err
}
log.Info("Generating ssh key pairs")
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
err = g.generatePrivateKey(privateKey)
if err != nil {
return err
}
return g.generatePublicKey(privateKey)
}
func (g *gitdb) generatePrivateKey(pk *rsa.PrivateKey) error {
// generate and write private key as PEM
privateKeyFile, err := os.OpenFile(g.privateKeyFilePath(), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0400)
defer privateKeyFile.Close()
if err != nil {
return err
}
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)}
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
return err
}
return nil
}
func (g *gitdb) generatePublicKey(pk *rsa.PrivateKey) error {
// generate and write public key
pub, err := ssh.NewPublicKey(&pk.PublicKey)
if err != nil {
return err
}
return ioutil.WriteFile(g.publicKeyFilePath(), ssh.MarshalAuthorizedKey(pub), 0655)
}