forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_by_ssh.go
89 lines (73 loc) · 1.59 KB
/
token_by_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
package hyperone
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"github.com/hashicorp/packer/common/json"
)
const (
sshAddress = "api.hyperone.com:22"
sshSubsystem = "rbx-auth"
hostKeyHash = "3e2aa423d42d7e8b14d50625512c8ac19db767ed"
)
type sshData struct {
ID string `json:"_id"`
}
func sshAgent() ssh.AuthMethod {
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
}
return nil
}
func fetchTokenBySSH(user string) (string, error) {
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
sshAgent(),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
hash := sha1Sum(key)
if hash != hostKeyHash {
return fmt.Errorf("invalid host key hash: %s", hash)
}
return nil
},
}
client, err := ssh.Dial("tcp", sshAddress, sshConfig)
if err != nil {
return "", err
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
stdout, err := session.StdoutPipe()
if err != nil {
return "", err
}
err = session.RequestSubsystem(sshSubsystem)
if err != nil {
return "", err
}
out, err := ioutil.ReadAll(stdout)
if err != nil {
return "", err
}
var data sshData
err = json.Unmarshal(out, &data)
if err != nil {
return "", err
}
return data.ID, nil
}
func sha1Sum(pubKey ssh.PublicKey) string {
sum := sha1.Sum(pubKey.Marshal())
return hex.EncodeToString(sum[:])
}