-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
59 lines (47 loc) · 1.56 KB
/
auth.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
package forwarder
import (
"fmt"
"os"
"golang.org/x/crypto/ssh"
)
// SetKeyFile changes the authentication to key-based and uses the specified file.
// Leaving the file empty defaults to the default linux private key locations: `~/.ssh/id_rsa`, `~/.ssh/id_dsa`,
// `~/.ssh/id_ecdsa`, `~/.ssh/id_ecdsa_sk`, `~/.ssh/id_ed25519` and `~/.ssh/id_ed25519_sk`.
func (tun *ForwardConfig) SetKeyFile(file string) *ForwardConfig {
tun.authKeyFile = file
return tun
}
// SetPort changes the port where the SSH connection will be made.
func (tun *ForwardConfig) SetPort(port int) *ForwardConfig {
tun.Server.port = port
return tun
}
func (tun *ForwardConfig) readPrivateKey(keyFile string) (ssh.AuthMethod, error) {
buf, err := os.ReadFile(keyFile)
if err != nil {
return nil, fmt.Errorf("reading SSH key file %s: %w", keyFile, err)
}
key, err := tun.parsePrivateKey(buf)
if err != nil {
return nil, fmt.Errorf("parsing SSH key file %s: %w", keyFile, err)
}
return key, nil
}
func (tun *ForwardConfig) parsePrivateKey(buf []byte) (ssh.AuthMethod, error) {
var key ssh.Signer
var err error
key, err = ssh.ParsePrivateKey(buf)
if err != nil {
return nil, fmt.Errorf("error parsing key: %w", err)
}
return ssh.PublicKeys(key), nil
}
func (tun *ForwardConfig) getSSHAuthMethodForKeyFile() (ssh.AuthMethod, error) {
if tun.authKeyFile != "" {
return tun.readPrivateKey(tun.authKeyFile)
}
return nil, fmt.Errorf("could not read SSH key %v", tun.authKeyFile)
}
func (tun *ForwardConfig) getSSHAuthMethod() (ssh.AuthMethod, error) {
return tun.getSSHAuthMethodForKeyFile()
}