/
initialize.go
188 lines (153 loc) · 3.92 KB
/
initialize.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
package initialize
import (
"context"
"errors"
"fmt"
"crypto"
"crypto/rand"
// "crypto/rsa"
"crypto/x509"
"encoding/pem"
"crypto/ecdsa"
"crypto/elliptic"
"golang.org/x/crypto/ssh"
"github.com/antony-jr/ham/internal/banner"
"github.com/antony-jr/ham/internal/core"
"github.com/antony-jr/ham/internal/helpers"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/mkideal/cli"
)
type initT struct {
cli.Helper
APIKey string `pw:"k,key" usage:"Hetzner API Key/Token for the project" prompt:"Hetzner API Key/Token"`
Force bool `cli:"f,force" usage:"Overwrite configuration even if exists."`
}
func NewCommand() *cli.Command {
return &cli.Command{
Name: "init",
Desc: "Initialize API connection to your Hetzner Project",
Argv: func() interface{} { return new(initT) },
Fn: func(ctx *cli.Context) error {
argv := ctx.Argv().(*initT)
banner.InitStartBanner()
configFilePath, err := helpers.ConfigFilePath()
if err != nil {
return errors.New("Failed to Get Config File Path")
}
if len(argv.APIKey) < 10 {
return errors.New("Invalid API Key")
}
privateKey, err := generatePrivateKey()
if err != nil {
return err
}
sshPublicKey, err := getSSHPublicKey(privateKey.Public())
if err != nil {
return err
}
privateKeyBytes, err := encodePrivateKeyToPEM(privateKey)
if err != nil {
return err
}
pks := string(sshPublicKey[:])
pks = fmt.Sprint(pks[:len(pks)-2])
config := core.NewConfiguration(
argv.APIKey,
fmt.Sprintf("%s= ham@antonyjr.in\n", pks),
string(privateKeyBytes[:]),
)
// Add the new sshkey and check connection with the API Key
client := hcloud.NewClient(hcloud.WithToken(config.APIKey))
sshkeys, err := client.SSHKey.All(
context.Background(),
)
if err != nil {
return err
}
// Search for ham-ssh-key SSH Key,
// if found then delete it if the user
// forces it.
keyExists := false
sshIdx := 0
for index, el := range sshkeys {
if el.Name == "ham-ssh-key" {
keyExists = true
sshIdx = index
break
}
}
if keyExists {
if !argv.Force {
return errors.New("SSH Key Already Exists at Server, Run with -f flag.")
}
// Delete the existing key first then add our new one.
_, err := client.SSHKey.Delete(
context.Background(),
sshkeys[sshIdx],
)
if err != nil {
return err
}
}
exists, err := helpers.FileExists(configFilePath)
if err != nil {
return err
}
if exists && !argv.Force {
return errors.New("Configuration Already Exists, Run with -f flag.")
}
labels := make(map[string]string)
// Add the new key now
_, _, err = client.SSHKey.Create(
context.Background(),
hcloud.SSHKeyCreateOpts{
"ham-ssh-key",
config.SSHPublicKey,
labels,
},
)
if err != nil {
return err
}
// Create Configuration File
err = core.WriteConfiguration(config)
if err != nil {
return errors.New("Cannot Write Configuration File")
}
banner.InitFinishBanner()
return nil
},
}
}
func generatePrivateKey() (*ecdsa.PrivateKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
return privateKey, nil
}
// encodePrivateKeyToPEM encodes Private Key from RSA to PEM format
func encodePrivateKeyToPEM(privateKey *ecdsa.PrivateKey) ([]byte, error) {
// Get ASN.1 DER format
privDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return []byte(""), err
}
// pem.Block
privBlock := pem.Block{
Type: "PRIVATE KEY",
Headers: nil,
Bytes: privDER,
}
// Private key in PEM format
privatePEM := pem.EncodeToMemory(&privBlock)
return privatePEM, nil
}
func getSSHPublicKey(publickey crypto.PublicKey) ([]byte, error) {
publicEdKey, err := ssh.NewPublicKey(publickey)
if err != nil {
return nil, err
}
pubKeyBytes := ssh.MarshalAuthorizedKey(publicEdKey)
return pubKeyBytes, nil
}