forked from dciangot/dodas-IAMClientRec
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
501 lines (386 loc) · 11.5 KB
/
main.go
File metadata and controls
501 lines (386 loc) · 11.5 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
package main
import (
"bufio"
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"text/template"
"github.com/awnumar/memguard"
"github.com/denisbrodbeck/machineid"
"github.com/gookit/color"
"github.com/rs/zerolog/log"
)
type WellKnown struct {
RegisterEndpoint string `json:"registration_endpoint"`
}
func GetRegisterEndpoint(endpoint string) (register_endpoint string){
var c http.Client
well_known := endpoint + "/.well-known/openid-configuration"
resp, err := c.Get(well_known)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
var wk WellKnown
errUnmarshall := json.Unmarshal(body, &wk)
if errUnmarshall != nil {
panic(errUnmarshall)
}
return string(wk.RegisterEndpoint)
}
func tryContainerMachineID() (machineID string, err error) {
// Ref: https://stackoverflow.com/questions/23513045/how-to-check-if-a-process-is-running-inside-docker-container
cgroupFile, err := os.Open("/proc/self/cgroup")
if err != nil {
return machineID, fmt.Errorf("cannot open cgroup: %w", err)
}
defer cgroupFile.Close()
var buff bytes.Buffer
_, err = buff.ReadFrom(cgroupFile)
if err != nil {
return machineID, fmt.Errorf("cannot read cgroup: %w", err)
}
for _, line := range strings.Split(buff.String(), "\n") {
if strings.Contains(line, "/docker/") {
parts := strings.Split(line, "/docker/")
if len(parts) != 2 {
return machineID, fmt.Errorf("not a valid docker container id: %w", err)
}
machineID = parts[1]
break
}
}
if machineID == "" {
return machineID, fmt.Errorf("docker container id not found: %w", err)
}
return machineID, nil
}
func CreateHash(key string) string {
log.Debug().Msg("create hash")
id, errID := machineid.ProtectedID("sts-wire")
if errID != nil {
if strings.Contains(errID.Error(), "open /etc/machine-id: no such file or directory") {
// TODO: get a unique uuid for containers:
// Ref: https://github.com/denisbrodbeck/machineid/issues/5
// Ref: https://github.com/panta/machineid/blob/master/id_linux.go
id, errID = tryContainerMachineID()
if errID != nil {
id = "notAMachine"
log.Debug().Str("machineID", id).Msg("Cannot find a docker container id")
} else {
log.Debug().Str("machineID", id).Msg("Found docker container id")
}
} else {
panic(errID)
}
}
hasher := hmac.New(md5.New, []byte(id))
_, errWrite := hasher.Write([]byte(key))
if errWrite != nil {
panic(errWrite)
}
return hex.EncodeToString(hasher.Sum(nil))
}
func Encrypt(data []byte, password *memguard.Enclave) []byte {
log.Debug().Msg("encryption - open enclave")
passphrase, errOpenEnclave := password.Open()
if errOpenEnclave != nil {
memguard.SafePanic(errOpenEnclave)
}
defer passphrase.Destroy() // Destroy the copy when we return
log.Debug().Msg("encryption - create cipher")
block, errNewCiper := aes.NewCipher([]byte(CreateHash(string(passphrase.Bytes()))))
if errNewCiper != nil {
panic(errNewCiper)
}
log.Debug().Msg("encryption - create block")
gcm, errNewGCM := cipher.NewGCM(block)
if errNewGCM != nil {
panic(errNewGCM.Error())
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
log.Debug().Msg("encryption - encode")
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext
}
func Decrypt(data []byte, password *memguard.Enclave) []byte {
log.Debug().Msg("decryption - open enclave")
passphrase, errOpenEnclave := password.Open()
if errOpenEnclave != nil {
memguard.SafePanic(errOpenEnclave)
}
defer passphrase.Destroy() // Destroy the copy when we return
log.Debug().Msg("decryption - create key")
key := []byte(CreateHash(string(passphrase.Bytes())))
log.Debug().Msg("decryption - create cipher")
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
log.Debug().Msg("decryption - create block")
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
log.Debug().Msg("decryption - decode")
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return plaintext
}
type IAMClientConfig struct {
CallbackURL string
Host string
Port int
ClientName string
}
type ClientResponse struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Endpoint string `json:"registration_client_uri"`
}
type InitClientConfig struct {
ConfDir string
ClientConfig IAMClientConfig
Scanner GetInputWrapper
HTTPClient http.Client
IAMServer string
ClientTemplate string
NoPWD bool
}
func (t *InitClientConfig) InitClient(instance string) (endpoint string, clientResponse ClientResponse, passwd *memguard.Enclave, err error) { //nolint:funlen,gocognit,lll
filename := t.ConfDir + "/" + instance + ".json"
log.Debug().Str("filename", filename).Msg("credentials - init client")
confFile, err := os.Open(filename)
switch {
case err != nil && err.Error() != "no such file or directory":
tmpl, errParser := template.New("client").Parse(t.ClientTemplate)
if errParser != nil {
panic(errParser)
}
var b bytes.Buffer
errExecute := tmpl.Execute(&b, t.ClientConfig)
if errExecute != nil {
panic(errExecute)
}
request := b.String()
log.Debug().Str("URL", request).Msg("credentials")
contentType := "application/json"
log.Debug().Str("REFRESH_TOKEN", os.Getenv("REFRESH_TOKEN")).Msg("credentials")
if t.IAMServer == "" {
endpoint, err = t.Scanner.GetInputString("Insert the IAM endpoint",
"https://iam-demo.cloud.cnaf.infn.it")
if err != nil {
panic(err)
}
} else if t.IAMServer != "" {
log.Debug().Str("IAM endpoint used", t.IAMServer).Msg("credentials")
color.Green.Printf("==> IAM endpoint used: %s\n", t.IAMServer)
endpoint = t.IAMServer
}
register := GetRegisterEndpoint(endpoint)
log.Debug().Str("IAM register url", register).Msg("credentials")
color.Green.Printf("==> IAM register url: %s\n", register)
resp, err := t.HTTPClient.Post(register, contentType, strings.NewReader(request))
if err != nil {
panic(err)
}
defer resp.Body.Close()
log.Debug().Int("StatusCode", resp.StatusCode).Str("Status", resp.Status).Msg("credentials")
var rbody bytes.Buffer
_, err = rbody.ReadFrom(resp.Body)
if err != nil {
log.Err(err).Msg("credentials - read body")
panic(err)
}
log.Debug().Str("body", rbody.String()).Msg("credentials")
errUnmarshall := json.Unmarshal(rbody.Bytes(), &clientResponse)
if errUnmarshall != nil {
panic(errUnmarshall)
}
clientResponse.Endpoint = endpoint
if !t.NoPWD { //nolint:nestif
var errGetPasswd error
// TODO: verify branch when REFRESH_TOKEN is passed and is not empty string
if os.Getenv("REFRESH_TOKEN") == "" {
passMsg := fmt.Sprintf("%s Insert a pasword for the secret's encryption: ", color.Yellow.Sprint("==>"))
passwd, errGetPasswd = t.Scanner.GetPassword(passMsg, false)
if errGetPasswd != nil {
panic(errGetPasswd)
}
} else {
passwd = memguard.NewEnclave([]byte("nopassword"))
}
dumpClient := Encrypt(rbody.Bytes(), passwd)
filename := t.ConfDir + "/" + instance + ".json"
curFile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Err(err).Msg("credentials - dump client")
panic(err)
}
_, err = curFile.Write(dumpClient)
if err != nil {
log.Err(err).Msg("credentials - dump client")
panic(err)
}
err = curFile.Close()
if err != nil {
log.Err(err).Msg("credentials - dump client")
panic(err)
}
}
case err == nil && !t.NoPWD:
var errGetPasswd error
defer confFile.Close()
var rbody bytes.Buffer
_, err = rbody.ReadFrom(confFile)
if err != nil {
log.Err(err).Msg("credentials - init client")
panic(err)
}
// TODO: verify branch when REFRESH_TOKEN is passed and is not empty string
if os.Getenv("REFRESH_TOKEN") == "" {
passMsg := fmt.Sprintf("%s Insert a pasword for the secret's decryption: ", color.Yellow.Sprint("==>"))
passwd, errGetPasswd = t.Scanner.GetPassword(passMsg, true)
if errGetPasswd != nil {
panic(errGetPasswd)
}
} else {
passwd = memguard.NewEnclave([]byte("nopassword"))
}
errUnmarshal := json.Unmarshal(Decrypt(rbody.Bytes(), passwd), &clientResponse)
if errUnmarshal != nil {
panic(errUnmarshal)
}
log.Debug().Str("response endpoint", clientResponse.Endpoint).Msg("credentials")
endpoint = strings.Split(clientResponse.Endpoint, "/register")[0]
default:
log.Err(err).Msg("credentials - init client")
panic(err)
}
if endpoint == "" {
panic("Something went wrong. No endpoint selected")
}
return endpoint, clientResponse, passwd, nil
}
type GetInputWrapper struct {
Scanner bufio.Reader
}
func (t *GetInputWrapper) GetInputString(question string, def string) (text string, err error) {
if def != "" {
fmt.Printf("%s %s (press enter for default [%s]):", color.Yellow.Sprint("|=>"), question, def)
text, err = t.Scanner.ReadString('\n')
if err != nil {
return "", fmt.Errorf("GetInputString %w", err)
}
text = strings.ReplaceAll(text, "\r\n", "")
text = strings.ReplaceAll(text, "\n", "")
if text == "" {
text = def
}
} else {
fmt.Printf("|=> %s:", question)
text, err = t.Scanner.ReadString('\n')
if err != nil {
return "", fmt.Errorf("GetInputString %w", err)
}
text = strings.ReplaceAll(text, "\n", "")
}
return text, nil
}
func main() {
inputReader := *bufio.NewReader(os.Stdin)
scanner := GetInputWrapper{
Scanner: inputReader,
}
instance := ""
if len(os.Args) > 1 {
instance = os.Args[1]
if instance == "-h" {
fmt.Println("dodas-IAMClientRec <client name>")
return
} else if instance == "" {
instance = "automatic"
}
} else {
instance = "automatic"
}
iamServer := ""
iamServer = os.Getenv("IAM_INSTANCE")
if iamServer == "" {
if len(os.Args) > 2 {
iamServer = os.Args[2]
}
}
if iamServer == "" {
fmt.Println("No IAM instance specified, please set env IAM_INSTANCE or use:")
fmt.Println("dodas-IAMClientRec <client name> <IAM instance>")
return
}
callback := os.Getenv("OAUTH_CALLBACK")
if callback == "" {
fmt.Println("No Service redirect callback url specified, please set env OAUTH_CALLBACK")
return
}
confDir := "." + instance
_, err := os.Stat(confDir)
if os.IsNotExist(err) {
os.Mkdir(confDir, os.ModePerm)
}
clientConfig := IAMClientConfig{
CallbackURL: callback,
ClientName: instance,
}
// Create a CA certificate pool and add cert.pem to it
//caCert, err := ioutil.ReadFile("MINIO.pem")
//if err != nil {
// log.Fatal(err)
//}
//caCertPool := x509.NewCertPool()
//caCertPool.AppendCertsFromPEM(caCert)
// Create the TLS Config with the CA pool and enable Client certificate validation
cfg := &tls.Config{
//ClientCAs: caCertPool,
InsecureSkipVerify: true,
}
//cfg.BuildNameToCertificate()
tr := &http.Transport{
TLSClientConfig: cfg,
}
httpClient := &http.Client{
Transport: tr,
}
clientIAM := InitClientConfig{
ConfDir: confDir,
ClientConfig: clientConfig,
Scanner: scanner,
HTTPClient: *httpClient,
IAMServer: iamServer,
ClientTemplate: ClientTemplate,
NoPWD: true,
}
_, clientResponse, _, err := clientIAM.InitClient(instance)
if err != nil {
panic(err)
}
fmt.Println(clientResponse.ClientID)
fmt.Println(clientResponse.ClientSecret)
}