/
ssh.go
303 lines (254 loc) · 7.71 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
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
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and IronCore contributors
// SPDX-License-Identifier: Apache-2.0
package bmc
import (
"context"
"fmt"
"net"
"regexp"
"strconv"
"strings"
"time"
expect "github.com/google/goexpect"
"github.com/google/uuid"
"github.com/hashicorp/go-multierror"
"golang.org/x/crypto/ssh"
"github.com/ironcore-dev/oob/internal/log"
)
func init() {
registerBMC(sshBMC)
}
func sshBMC(tags map[string]string, host string, port int, creds Credentials, exp time.Time) BMC {
return &SSHBMC{
tags: tags,
host: host,
port: port,
creds: creds,
exp: exp,
}
}
func (b *SSHBMC) Type() string {
return "SSH"
}
func (b *SSHBMC) Tags() map[string]string {
return b.tags
}
func (b *SSHBMC) Credentials() (Credentials, time.Time) {
return b.creds, b.exp
}
type SSHBMC struct {
tags map[string]string
host string
port int
creds Credentials
exp time.Time
}
var sshscript = `for i in $(find /sys/class/dmi/id/ -type f); do
echo "$(basename $i):$(sudo cat $i 2> /dev/null)"
done`
var fields = map[string]string{
"UUID": "product_uuid",
"ChassisSerial": "chassis_serial",
"ProductSerial": "product_serial",
"Manufacturer": "chassis_vendor",
"SKU": "product_sku",
}
var namespaceForUUID = "ironcore.dev"
func sshConnect(ctx context.Context, host string, port int, creds Credentials) (*ssh.Client, error) {
log.Debug(ctx, "Connecting via SSH", "host", host, "user", creds.Username)
sshConfig := &ssh.ClientConfig{
User: creds.Username,
Auth: []ssh.AuthMethod{ssh.Password(creds.Password)},
}
sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
if port == 0 {
port = 22
}
hostAndPort := net.JoinHostPort(host, strconv.Itoa(port))
client, err := ssh.Dial("tcp", hostAndPort, sshConfig)
if err != nil {
return nil, fmt.Errorf("cannot connect: %w", err)
}
return client, nil
}
func sshRunCommand(_ context.Context, c *ssh.Client, command string) (string, error) {
session, err := c.NewSession()
if err != nil {
return "", fmt.Errorf("cannot create a SSH session: %w", err)
}
defer func() { _ = session.Close() }()
out, err := session.Output(command)
if err != nil {
return "", err
}
return strings.TrimSuffix(string(out), "\n"), err
}
func verifyLinux(ctx context.Context, c *ssh.Client) (bool, error) {
out, err := sshRunCommand(ctx, c, "uname")
if err != nil {
return false, fmt.Errorf("cannot verify that host is a Linux machine: %w", err)
}
if out == "Linux" {
return true, nil
}
return false, nil
}
func sshFindWorkingCredentials(ctx context.Context, host string, port int, defaultCreds []Credentials, tempPassword string) (Credentials, error) {
if len(defaultCreds) == 0 {
return Credentials{}, fmt.Errorf("no default credentials to try")
}
var merr error
for _, creds := range defaultCreds {
c, err := sshConnect(ctx, host, port, creds)
if err == nil {
err = c.Close()
if err == nil {
return creds, nil
}
}
merr = multierror.Append(merr, err)
}
for _, creds := range defaultCreds {
c, err := sshConnect(ctx, host, port, Credentials{creds.Username, tempPassword})
if err == nil {
err = c.Close()
if err == nil {
return creds, nil
}
}
merr = multierror.Append(merr, err)
}
return Credentials{}, fmt.Errorf("cannot connect using any predefined credentials: %w", merr)
}
func (b *SSHBMC) EnsureInitialCredentials(ctx context.Context, defaultCreds []Credentials, tempPassword string) error {
// No special stuff needed here, no initial password change and so on
creds, err := sshFindWorkingCredentials(ctx, b.host, b.port, defaultCreds, tempPassword)
if err != nil {
return err
}
b.creds = creds
return nil
}
func (b *SSHBMC) Connect(ctx context.Context) error {
c, err := sshConnect(ctx, b.host, b.port, b.creds)
if err != nil {
return err
}
_ = c.Close()
return nil
}
func (b *SSHBMC) ReadInfo(ctx context.Context) (Info, error) {
info := make(map[string]string)
c, err := sshConnect(ctx, b.host, b.port, b.creds)
if err != nil {
return Info{}, err
}
defer func() { must(ctx, c.Close()) }()
vl, err := verifyLinux(ctx, c)
if err != nil {
return Info{}, fmt.Errorf("cannot read machine info: %w", err)
}
if !vl {
return Info{}, fmt.Errorf("cannot read machine info from non Linux system")
}
out, err := sshRunCommand(ctx, c, sshscript)
if err != nil {
return Info{}, err
}
outputmap(out, &info)
ruuid := info[fields["UUID"]]
serial := info[fields["ProductSerial"]]
if serial == "" || serial == "None" {
serial = info[fields["ChassisSerial"]]
}
uuidSource := b.tags["uuidSrc"]
if uuidSource != "" {
s, ok := fields[uuidSource]
if !ok {
return Info{}, fmt.Errorf("no such field exists: %s", uuidSource)
}
namespaceUUID := uuid.NewMD5(uuid.UUID{}, []byte(namespaceForUUID))
guuid := uuid.NewMD5(namespaceUUID, []byte(info[s]))
ruuid = guuid.String()
}
ruuid = strings.ToLower(ruuid)
return Info{
UUID: ruuid,
Type: "",
Capabilities: []string{"credentials"},
SerialNumber: serial,
SKU: info[fields["SKU"]],
Manufacturer: info[fields["Manufacturer"]],
Power: "On",
}, nil
}
func sshUserAddCommand(user string) string {
useradd := fmt.Sprintf(`(sudo adduser %s --gecos "GOM" --disabled-password || sudo useradd -b /home/%s -s /bin/sh -m %s)`, user, user, user)
usermod := fmt.Sprintf(`sudo usermod -aG $(awk -F: '$1 ~ /sudo|wheel/{printf "%%s%%s", s, $1; s=","}' /etc/group) %s`, user)
chage := fmt.Sprintf(`sudo chage -E -1 -M -1 %s`, user)
return fmt.Sprintf(`%s && %s && %s`, useradd, usermod, chage)
}
func (b *SSHBMC) CreateUser(ctx context.Context, creds Credentials, _ string) error {
client, err := sshConnect(ctx, b.host, b.port, b.creds)
if err != nil {
return err
}
_, err = sshRunCommand(ctx, client, sshUserAddCommand(creds.Username))
if err != nil {
return fmt.Errorf("cannot add username %s on host %s: %w", creds.Username, b.host, err)
}
err = sshChangePassword(ctx, b.host, b.port, b.creds, creds)
if err != nil {
return err
}
b.creds = creds
b.exp = time.Time{}
return nil
}
func sshChangePassword(ctx context.Context, host string, port int, creds, newCreds Credentials) error {
client, err := sshConnect(ctx, host, port, creds)
if err != nil {
return err
}
defer func() { must(ctx, client.Close()) }()
timeout := 5 * time.Second
e, _, err := expect.SpawnSSH(client, timeout, expect.Verbose(false), expect.PartialMatch(true))
if err != nil {
return fmt.Errorf("cannot spawn SSH client: %w", err)
}
defer func() { must(ctx, e.Close()) }()
_, err = e.ExpectBatch([]expect.Batcher{
&expect.BSnd{S: "sudo passwd " + newCreds.Username + "\n"},
&expect.BExp{R: "New password:"},
&expect.BSnd{S: newCreds.Password + "\n"},
&expect.BExp{R: "Retype new password:"},
&expect.BSnd{S: newCreds.Password + "\n"},
&expect.BExp{R: "passwd: password updated successfully"},
}, timeout)
if err != nil {
return fmt.Errorf("cannot change the password for user %s on host %s: %w", newCreds.Username, host, err)
}
return nil
}
func (b *SSHBMC) DeleteUsers(ctx context.Context, regex *regexp.Regexp) error {
client, err := sshConnect(ctx, b.host, b.port, b.creds)
if err != nil {
return err
}
out, err := sshRunCommand(ctx, client, "getent passwd | cut -d: -f1")
if err != nil {
return fmt.Errorf("cannot list the users on host: %s: %w", b.host, err)
}
users := strings.Split(out, "\n")
for _, user := range users {
if user != b.creds.Username && regex.MatchString(user) {
// TODO: enable actual deletion
//_, err = sshRunCommand(ctx, client, fmt.Sprintf("sudo userdel -fr %s", user))
_, err = sshRunCommand(ctx, client, fmt.Sprintf("echo %s", user))
if err != nil {
return fmt.Errorf("unable to delete user %s on host %s: %w", user, b.host, err)
}
}
}
return nil
}