-
Notifications
You must be signed in to change notification settings - Fork 1
/
ndb.go
332 lines (277 loc) · 9.35 KB
/
ndb.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
package agent
import (
"bufio"
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
var (
// FIXME: Look into whether log.Logger is okay or whether to use logrus.Logger
Ldebug *log.Logger
Linfo *log.Logger
Lerror *log.Logger
)
// NetworkCredentials is the network informations.
type NetworkCredentials struct {
Name string `json:"name"`
APIsrv string `json:"api_srv"`
PVkey string `json:"pvkey"`
Cert string `json:"cert"`
CAcert string `json:"cacert"`
}
// provInformation is the provisioning information contains in the prov link
type provInformation struct {
Version string
APIsrv string
NetworkUID string
NodeUID string
Key string
}
// csrRequest is the Certificate Signing Request
type csrRequest struct {
CSR string `json:"csr"`
ProvLink string `json:"provlink"`
}
// Ndb is the network database.
type Ndb struct {
Version int `json:"version"`
Networks []NetworkCredentials `json:"networks"`
}
// GetNdbPath returns the path of the network database.
func GetNdbPath() string {
// FIXME make it works on Windows too
return os.Getenv("HOME") + "/.config/netvfy/nvagent.json"
}
// FetchNetworks returns a populated network database object.
func FetchNetworks(ndbPath string) (*Ndb, error) {
// Read the network database
byteValue, err := ioutil.ReadFile(ndbPath)
if err != nil {
return nil, fmt.Errorf("FetchNetworks: failed to read the network database: %v", err)
}
var ndb Ndb
err = json.Unmarshal(byteValue, &ndb)
if err != nil {
return nil, fmt.Errorf("FetchNetworks: failed to unmarshal the network database: %v", err)
}
return &ndb, nil
}
// GetNetworkCred returns the credentials of the specified network name if the network exist
func GetNetworkCred(networkName string) (*NetworkCredentials, error) {
// Read the configuration file
byteValue, err := ioutil.ReadFile(GetNdbPath())
if err != nil {
return nil, fmt.Errorf("GetNetworkCred: failed to read the configuration file: %v", err)
}
var netConf Ndb
err = json.Unmarshal(byteValue, &netConf)
if err != nil {
return nil, fmt.Errorf("GetNetworkCred: failed to unmarshal the network configuration: %v", err)
}
// Find the network in the list
for i := 0; i < len(netConf.Networks); i++ {
networkCred := netConf.Networks[i]
if networkCred.Name == networkName {
return &networkCred, nil
}
}
// Nothing found
return nil, nil
}
// DeleteNetwork delete the network specified in parameter
func DeleteNetwork(networkName string) error {
// Read the configuration file
byteValue, err := ioutil.ReadFile(GetNdbPath())
if err != nil {
return fmt.Errorf("DeleteNetwork: failed to read the configuration file: %v", err)
}
var ndb Ndb
err = json.Unmarshal(byteValue, &ndb)
if err != nil {
return fmt.Errorf("DeleteNetwork: failed to unmarshal the network configuration: %v", err)
}
// Find the network to delete
var found bool
for i := 0; i < len(ndb.Networks); i++ {
if ndb.Networks[i].Name == networkName {
ndb.Networks = append(ndb.Networks[:i], ndb.Networks[i+1:]...)
found = true
break
}
}
if !found {
return fmt.Errorf("DeleteNetwork: failed to delete network: `%v`: not found", networkName)
}
marshaledJSON, err := json.MarshalIndent(ndb, "", " ")
if err != nil {
return fmt.Errorf("DeleteNetwork: failed to marshal the network configuration: %v", err)
}
// FIXME: determine what permissions are necessary and add single var or constant in package
err = ioutil.WriteFile(GetNdbPath(), marshaledJSON, 0644)
if err != nil {
return fmt.Errorf("DeleteNetwork: failed to save the network configuration: %v", err)
}
return nil
}
// ProvisionNetwork provision a new network based on the provisioned linked
func ProvisionNetwork(provLink string, networkName string) error {
var marshaledJSON []byte
cred, _ := GetNetworkCred(networkName)
if cred != nil {
return fmt.Errorf("ProvisionNetwork: the network name already exist: %s", networkName)
}
Ldebug.Printf("provLink: %s\n", provLink)
// Parse the provisioning link
u, err := url.Parse(provLink)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to parse the provisioning link: %v", err)
}
Ldebug.Printf("Parsed provisioning link: %v\n", u.RawQuery)
values, err := url.ParseQuery(u.RawQuery)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to parse the query string: %v", err)
}
// Extract the fields from the provisioning link
// FIXME create a function that validate and return a provInfo
provInfo := provInformation{
Version: values.Get("v"),
APIsrv: values.Get("a"),
NetworkUID: values.Get("w"),
NodeUID: values.Get("n"),
Key: values.Get("k"),
}
if provInfo.Version == "" {
return fmt.Errorf("ProvisionNetwork: failed to find the version from the provisioning link")
}
if provInfo.APIsrv == "" {
return fmt.Errorf("ProvisionNetwork: failed to find the API server from the provisioning link")
}
if provInfo.NetworkUID == "" {
return fmt.Errorf("ProvisionNetwork: failed to find the network UID from the provisioning link")
}
if provInfo.NodeUID == "" {
return fmt.Errorf("ProvisionNetwork: failed to find the node UID from the provisioning link")
}
if provInfo.Key == "" {
return fmt.Errorf("ProvisionNetwork: failed to find the key from the provisioning link")
}
// Read the configuration into netConf
var netConf Ndb
data, err := ioutil.ReadFile(GetNdbPath())
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// Since the file doesn't exist, we
// initialize the netConf structure that will
// be written to a new file
netConf.Version = 1
} else {
return fmt.Errorf("ProvisionNetwork: failed to read the configuration file: %v", err)
}
} else {
err = json.Unmarshal(data, &netConf)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to unmarshal the network configuration: %v", err)
}
}
// Generate a new public/private key pair
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to generate new key pair: %v", err)
}
// Prepare a Certificate Signing Request
// FIXME: make this a package wide constant
name := pkix.Name{
CommonName: "netvfy-agent",
}
csrTemplate := x509.CertificateRequest{
Subject: name,
SignatureAlgorithm: x509.ECDSAWithSHA512,
}
csrCertificate, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, privKey)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to generate the Certificate Signing Request: %v", err)
}
csr := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST", Bytes: csrCertificate,
})
Ldebug.Printf("CSR: %s\n", csr)
// Prepare the HTTP request asking to sign our CSR
req := csrRequest{
CSR: string(csr),
ProvLink: provLink,
}
jreq, err := json.Marshal(req)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to marshal the Certificate Signing Request request: %v", err)
}
Ldebug.Printf("CSR request: %s\n", jreq)
client := http.Client{
Timeout: time.Duration(5 * time.Second),
}
request, err := http.NewRequest("POST", "https://"+provInfo.APIsrv+"/v1/provisioning", bytes.NewBuffer(jreq))
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to create the http new request: %v", err)
}
request.Header.Set("Content-Type", "application/json")
resp, err := client.Do(request)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to perform the http request: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to read the query response: %v", err)
}
// Unmarshal the CSR response
var networkCred NetworkCredentials
err = json.Unmarshal(body, &networkCred)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to unmarshal the provisioning response: %v", err)
}
// If no network name was provided, ask for one
networkCred.Name = networkName
if networkCred.Name == "" {
Linfo.Print("Enter the name of the new network: ")
reader := bufio.NewReader(os.Stdin)
// ReadString will block until the delimiter is entered
networkCred.Name, err = reader.ReadString('\n')
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to read the entered network name: %v", err)
}
networkCred.Name = strings.TrimRight(networkCred.Name, "\r\n")
}
networkCred.APIsrv = provInfo.APIsrv
// Convert private key in string format to be saved in the configuration file
x509Encoded, _ := x509.MarshalECPrivateKey(privKey)
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
networkCred.PVkey = string(pemEncoded)
Ldebug.Printf("cert:\n%s\n", networkCred.Cert)
Ldebug.Printf("CAcert:\n%s\n", networkCred.CAcert)
netConf.Networks = append(netConf.Networks, networkCred)
marshaledJSON, err = json.MarshalIndent(netConf, "", " ")
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to marshal the network configuration: %v", err)
}
os.MkdirAll(filepath.Dir(GetNdbPath()), os.ModePerm)
// FIXME: determine what permissions are necessary and add single var or constant in package
err = ioutil.WriteFile(GetNdbPath(), marshaledJSON, 0644)
if err != nil {
return fmt.Errorf("ProvisionNetwork: failed to save the network configuration: %v", err)
}
return nil
}