-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathauth.go
More file actions
419 lines (349 loc) · 11.6 KB
/
auth.go
File metadata and controls
419 lines (349 loc) · 11.6 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
// Copyright (c) 2026 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
// TODO(blacknon):
// ↓等を読み解いて、Publickey offeringやknown_hostsのチェックを実装する(`v0.2.0`)。
// 既存のライブラリ等はないので、自前でrequestを書く必要があるかも?
// かなりの手間がかかりそうなので、対応については相応に時間がかかりそう。
// - https://go.googlesource.com/crypto/+/master/ssh/client_auth.go
// - https://go.googlesource.com/crypto/+/master/ssh/tcpip.go
package sshlib
import (
"fmt"
"os"
"regexp"
"strings"
"sync"
"unsafe"
"github.com/ScaleFT/sshkeys"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
type ControlPersistAuth struct {
// AuthMethods allows reusing auth methods created by sshlib helper functions
// such as CreateAuthMethodPassword/CreateAuthMethodPublicKey.
AuthMethods []ssh.AuthMethod `json:"-"`
// Methods stores serializable auth definitions for detached ControlPersist
// helpers and proxy routes.
Methods []ControlPersistAuthMethod
}
type ControlPersistAuthMethod struct {
Type string
Password string
KeyPath string
KeyPass string
Transient bool
PKCS11Provider string
PKCS11PIN string
}
type authMethodRegistryKey struct {
typ uintptr
data uintptr
}
type controlPersistAuthMethodDefinition struct {
Type string
Password string
KeyPath string
KeyPass string
Transient bool
PKCS11Provider string
PKCS11PIN string
}
var controlPersistAuthMethodRegistry sync.Map
func (a *ControlPersistAuth) resolved() ([]controlPersistAuthMethodDefinition, error) {
if a == nil {
return nil, fmt.Errorf("sshlib: ControlPersistAuth is required for detached ControlPersist helper")
}
if len(a.Methods) > 0 {
resolved := make([]controlPersistAuthMethodDefinition, 0, len(a.Methods))
for _, method := range a.Methods {
resolved = append(resolved, controlPersistAuthMethodDefinition{
Type: method.Type,
Password: method.Password,
KeyPath: method.KeyPath,
KeyPass: method.KeyPass,
Transient: method.Transient,
PKCS11Provider: method.PKCS11Provider,
PKCS11PIN: method.PKCS11PIN,
})
}
if err := validateControlPersistAuthDefinitions(resolved); err != nil {
return nil, err
}
return resolved, nil
}
if len(a.AuthMethods) == 0 {
return nil, fmt.Errorf("sshlib: ControlPersistAuth.AuthMethods is required for detached ControlPersist helper")
}
resolved := make([]controlPersistAuthMethodDefinition, 0, len(a.AuthMethods))
for _, authMethod := range a.AuthMethods {
persistAuth, ok := lookupControlPersistAuthMethod(authMethod)
if !ok {
return nil, fmt.Errorf("sshlib: unsupported authMethod for ControlPersistAuth; use sshlib.CreateAuthMethodPassword/CreateAuthMethodPublicKey")
}
resolved = append(resolved, *persistAuth)
}
return resolved, nil
}
func createControlPersistAuthMethods(definitions []controlPersistAuthMethodDefinition) ([]ssh.AuthMethod, error) {
return createControlPersistAuthMethodsWithPrompt(definitions, nil)
}
func createControlPersistAuthMethodsWithPrompt(definitions []controlPersistAuthMethodDefinition, prompt PromptFunc) ([]ssh.AuthMethod, error) {
if err := validateControlPersistAuthDefinitions(definitions); err != nil {
return nil, err
}
transientKeyPaths := make([]string, 0, len(definitions))
defer func() {
cleanupControlPersistTransientFiles(transientKeyPaths)
}()
authMethods := make([]ssh.AuthMethod, 0, len(definitions))
for _, persistAuth := range definitions {
switch persistAuth.Type {
case "password":
authMethods = append(authMethods, CreateAuthMethodPassword(persistAuth.Password))
case "publickey":
auth, err := CreateAuthMethodPublicKey(persistAuth.KeyPath, persistAuth.KeyPass)
if err != nil {
return nil, err
}
if persistAuth.Transient {
transientKeyPaths = append(transientKeyPaths, persistAuth.KeyPath)
}
authMethods = append(authMethods, auth)
case "pkcs11":
auth, err := CreateAuthMethodPKCS11WithPrompt(persistAuth.PKCS11Provider, persistAuth.PKCS11PIN, prompt)
if err != nil {
return nil, err
}
authMethods = append(authMethods, auth...)
default:
return nil, fmt.Errorf("sshlib: unsupported ControlPersistAuth type %q", persistAuth.Type)
}
}
return authMethods, nil
}
func cleanupControlPersistTransientFiles(paths []string) {
if len(paths) == 0 {
return
}
seen := make(map[string]struct{}, len(paths))
for _, path := range paths {
if path == "" {
continue
}
absPath := getAbsPath(path)
if _, ok := seen[absPath]; ok {
continue
}
seen[absPath] = struct{}{}
_ = os.Remove(absPath)
}
}
func validateControlPersistAuthDefinitions(definitions []controlPersistAuthMethodDefinition) error {
if len(definitions) == 0 {
return fmt.Errorf("sshlib: ControlPersistAuth.AuthMethods is required for detached ControlPersist helper")
}
for _, persistAuth := range definitions {
switch persistAuth.Type {
case "password":
if persistAuth.Password == "" {
return fmt.Errorf("sshlib: password auth requires Password")
}
case "publickey":
if persistAuth.KeyPath == "" {
return fmt.Errorf("sshlib: publickey auth requires KeyPath")
}
case "pkcs11":
if persistAuth.PKCS11Provider == "" {
return fmt.Errorf("sshlib: pkcs11 auth requires PKCS11Provider")
}
default:
return fmt.Errorf("sshlib: unsupported ControlPersistAuth type %q", persistAuth.Type)
}
}
return nil
}
func registerControlPersistAuthMethod(auth ssh.AuthMethod, persistAuth controlPersistAuthMethodDefinition) {
key, ok := controlPersistAuthMethodKey(auth)
if !ok {
return
}
controlPersistAuthMethodRegistry.Store(key, persistAuth)
}
func lookupControlPersistAuthMethod(auth ssh.AuthMethod) (*controlPersistAuthMethodDefinition, bool) {
key, ok := controlPersistAuthMethodKey(auth)
if !ok {
return nil, false
}
value, ok := controlPersistAuthMethodRegistry.Load(key)
if !ok {
return nil, false
}
persistAuth, ok := value.(controlPersistAuthMethodDefinition)
if !ok {
return nil, false
}
return &persistAuth, true
}
func controlPersistAuthMethodKey(auth ssh.AuthMethod) (authMethodRegistryKey, bool) {
if auth == nil {
return authMethodRegistryKey{}, false
}
representation := *(*[2]uintptr)(unsafe.Pointer(&auth))
if representation[1] == 0 {
return authMethodRegistryKey{}, false
}
return authMethodRegistryKey{
typ: representation[0],
data: representation[1],
}, true
}
// CreateAuthMethodPassword returns ssh.AuthMethod generated from password.
func CreateAuthMethodPassword(password string) (auth ssh.AuthMethod) {
auth = ssh.Password(password)
registerControlPersistAuthMethod(auth, controlPersistAuthMethodDefinition{
Type: "password",
Password: password,
})
return
}
// CreateAuthMethodPublicKey returns ssh.AuthMethod generated from PublicKey.
// If you have not specified a passphrase, please specify a empty character("").
func CreateAuthMethodPublicKey(key, password string) (auth ssh.AuthMethod, err error) {
return createAuthMethodPublicKey(key, password, false)
}
// CreateAuthMethodPublicKeyTransient returns ssh.AuthMethod generated from PublicKey.
// The serialized ControlPersist definition is marked as transient, so detached
// helpers remove the key file after rebuilding the signer in memory.
func CreateAuthMethodPublicKeyTransient(key, password string) (auth ssh.AuthMethod, err error) {
return createAuthMethodPublicKey(key, password, true)
}
func createAuthMethodPublicKey(key, password string, transient bool) (auth ssh.AuthMethod, err error) {
signer, err := CreateSignerPublicKey(key, password)
if err != nil {
return
}
auth = ssh.PublicKeys(signer)
registerControlPersistAuthMethod(auth, controlPersistAuthMethodDefinition{
Type: "publickey",
KeyPath: key,
KeyPass: password,
Transient: transient,
})
return
}
// CreateSignerPublicKey returns []ssh.Signer generated from public key.
// If you have not specified a passphrase, please specify a empty character("").
func CreateSignerPublicKey(key, password string) (signer ssh.Signer, err error) {
// get absolute path
key = getAbsPath(key)
// Read PrivateKey file
keyData, err := os.ReadFile(key)
if err != nil {
return
}
signer, err = CreateSignerPublicKeyData(keyData, password)
return
}
// CreateSignerPublicKeyData return ssh.Signer from private key and password
func CreateSignerPublicKeyData(keyData []byte, password string) (signer ssh.Signer, err error) {
if password != "" { // password is not empty
// Parse key data
data, err := sshkeys.ParseEncryptedRawPrivateKey(keyData, []byte(password))
if err != nil {
return signer, err
}
// Create ssh.Signer
signer, err = ssh.NewSignerFromKey(data)
} else { // password is empty
signer, err = ssh.ParsePrivateKey(keyData)
}
return
}
// CreateSignerPublicKeyPrompt rapper CreateSignerPKCS11.
// Output a passphrase input prompt if the passphrase is not entered or incorrect.
//
// Only Support UNIX-like OS.
func CreateSignerPublicKeyPrompt(key, password string) (signer ssh.Signer, err error) {
// repeat count
rep := 3
// get absolute path
key = getAbsPath(key)
// Read PrivateKey file
keyData, err := os.ReadFile(key)
if err != nil {
return
}
if password != "" { // password is not empty
signer, err = ssh.ParsePrivateKeyWithPassphrase(keyData, []byte(password))
} else { // password is empty
signer, err = ssh.ParsePrivateKey(keyData)
rgx := regexp.MustCompile(`cannot decode`)
if err != nil {
if rgx.MatchString(err.Error()) {
msg := key + "'s passphrase:"
for i := 0; i < rep; i++ {
password, _ = getPassphrase(msg)
password = strings.TrimRight(password, "\n")
signer, err = ssh.ParsePrivateKeyWithPassphrase(keyData, []byte(password))
if err == nil {
return
}
fmt.Println("\n" + err.Error())
}
}
}
}
return
}
// CreateAuthMethodCertificate returns ssh.AuthMethod generated from Certificate.
// To generate an AuthMethod from a certificate, you will need the certificate's private key Signer.
// Signer should be generated from CreateSignerPublicKey() or CreateSignerPKCS11().
func CreateAuthMethodCertificate(cert string, keySigner ssh.Signer) (auth ssh.AuthMethod, err error) {
signer, err := CreateSignerCertificate(cert, keySigner)
if err != nil {
return
}
auth = ssh.PublicKeys(signer)
return
}
// CreateSignerCertificate returns ssh.Signer generated from Certificate.
// To generate an AuthMethod from a certificate, you will need the certificate's private key Signer.
// Signer should be generated from CreateSignerPublicKey() or CreateSignerPKCS11().
func CreateSignerCertificate(cert string, keySigner ssh.Signer) (certSigner ssh.Signer, err error) {
// get absolute path
cert = getAbsPath(cert)
// Read Cert file
certData, err := os.ReadFile(cert)
if err != nil {
return
}
// Create PublicKey from Cert
pubkey, _, _, _, err := ssh.ParseAuthorizedKey(certData)
if err != nil {
return
}
// Create Certificate Struct
certificate, ok := pubkey.(*ssh.Certificate)
if !ok {
err = fmt.Errorf("%s\n", "Error: Not create certificate struct data")
return
}
// Create Certificate Signer
certSigner, err = ssh.NewCertSigner(certificate, keySigner)
if err != nil {
return
}
return
}
// CreateSignerAgent return []ssh.Signer from ssh-agent.
// In sshAgent, put agent.Agent or agent.ExtendedAgent.
func CreateSignerAgent(sshAgent interface{}) (signers []ssh.Signer, err error) {
switch ag := sshAgent.(type) {
case agent.Agent:
signers, err = ag.Signers()
case agent.ExtendedAgent:
signers, err = ag.Signers()
}
return
}