/
login.go
189 lines (153 loc) · 3.94 KB
/
login.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
// Copyright (c) 2021-2022, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0
package cmd
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/choria-io/go-choria/choria"
)
type loginCommand struct {
command
}
func (p *loginCommand) Setup() error {
p.cmd = cli.app.Command("login", "Authenticate against the Choria AAA System")
p.cmd.Flag("config", "Config file to use").PlaceHolder("FILE").StringVar(&configFile)
return nil
}
func (p *loginCommand) Configure() error {
return commonConfigure()
}
func (p *loginCommand) Run(wg *sync.WaitGroup) error {
defer wg.Done()
ext, _ := exec.LookPath("choria-login")
if ext != "" {
return p.runExternal(ext)
}
return p.login()
}
func (p *loginCommand) sign(user string, pass string, timeStamp string) (signature string, pub string, err error) {
seed, err := c.SignerSeedFile()
if err != nil {
return "", "", err
}
pubK, priK, err := choria.Ed25519KeyPairToFile(seed)
if err != nil {
return "", "", fmt.Errorf("could not generate keypair: %s", err)
}
sig, err := choria.Ed25519Sign(priK, []byte(fmt.Sprintf("%s:%s:%s", timeStamp, user, pass)))
if err != nil {
return "", "", fmt.Errorf("could not sign request: %s", err)
}
return hex.EncodeToString(sig), hex.EncodeToString(pubK), nil
}
func (p *loginCommand) login() error {
loginURLs := cfg.Choria.AAAServiceLoginURLs
if len(loginURLs) == 0 {
return fmt.Errorf("please configure a login server URL using plugin.login.aaasvc.login.url")
}
token, err := c.SignerTokenFile()
if err != nil {
return fmt.Errorf("no token path found: %v", err)
}
user := ""
pass := ""
err = survey.AskOne(&survey.Input{Message: "Username: ", Default: os.Getenv("USER")}, &user, survey.WithValidator(survey.Required))
if err != nil {
return err
}
err = survey.AskOne(&survey.Password{Message: "Password: "}, &pass, survey.WithValidator(survey.Required))
if err != nil {
return err
}
abs, err := filepath.Abs(token)
if err != nil {
return fmt.Errorf("cannot determine parent directory for token file: %s", err)
}
err = os.MkdirAll(filepath.Dir(abs), 0700)
if err != nil {
return err
}
nowString := strconv.Itoa(int(time.Now().Unix()))
sig, pub, err := p.sign(user, pass, nowString)
if err != nil {
return err
}
request := map[string]any{
"username": user,
"password": pass,
"signature": sig,
"public_key": pub,
"timestamp": nowString,
}
jr, err := json.Marshal(&request)
if err != nil {
return err
}
rand.Shuffle(len(loginURLs), func(i, j int) { loginURLs[i], loginURLs[j] = loginURLs[j], loginURLs[i] })
uri, err := url.Parse(loginURLs[0])
if err != nil {
return err
}
client := &http.Client{}
if uri.Scheme == "https" {
tlsc, err := c.ClientTLSConfig()
if err != nil {
return err
}
client.Transport = &http.Transport{TLSClientConfig: tlsc}
}
resp, err := client.Post(uri.String(), "application/json", bytes.NewBuffer(jr))
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("invalid response code %d: %s", resp.StatusCode, string(body))
}
login := map[string]string{}
err = json.Unmarshal(body, &login)
if err != nil {
return err
}
if login["error"] != "" {
return fmt.Errorf(login["error"])
}
if login["token"] == "" {
return fmt.Errorf("no token received")
}
err = os.WriteFile(abs, []byte(login["token"]), 0600)
if err != nil {
return err
}
fmt.Printf("Token saved to %s\n", abs)
return nil
}
func (p *loginCommand) runExternal(ext string) error {
cmd := exec.Command(ext, os.Args[1:]...)
cmd.Env = os.Environ()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
func init() {
cli.commands = append(cli.commands, &loginCommand{})
}