aboutsummaryrefslogtreecommitdiffstats
path: root/test/security/k8s/src/check/raw/raw.go
blob: 3c5409aeee3cccc291854eaf4466a950dad8c5fc (plain)
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
// Package raw wraps SSH commands necessary for K8s inspection.
package raw

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os/user"
	"path/filepath"

	"golang.org/x/crypto/ssh"
	kh "golang.org/x/crypto/ssh/knownhosts"

	"check"
	"check/config"
)

const (
	controlplane = "controlplane"
	etcd         = "etcd"
	worker       = "worker"

	knownHostsFile = "~/.ssh/known_hosts"
)

// Raw implements Informer interface.
type Raw struct {
	check.Informer
}

// GetAPIParams returns parameters of running Kubernetes API servers.
// It queries only cluster nodes with "controlplane" role.
func (r *Raw) GetAPIParams() ([]string, error) {
	return getProcessParams(check.APIProcess)
}

// GetSchedulerParams returns parameters of running Kubernetes scheduler.
// It queries only cluster nodes with "controlplane" role.
func (r *Raw) GetSchedulerParams() ([]string, error) {
	return getProcessParams(check.SchedulerProcess)
}

func getProcessParams(process check.Command) ([]string, error) {
	nodes, err := config.GetNodesInfo()
	if err != nil {
		return []string{}, err
	}

	for _, node := range nodes {
		if isControlplaneNode(node.Role) {
			cmd, err := getInspectCmdOutput(node, process)
			if err != nil {
				return []string{}, err
			}

			if len(cmd) > 0 {
				i := bytes.Index(cmd, []byte(process.String()))
				if i == -1 {
					return []string{}, fmt.Errorf("missing %s command", process)
				}
				return btos(cmd[i+len(process.String()):]), nil
			}
		}
	}

	return []string{}, nil
}

func isControlplaneNode(roles []string) bool {
	for _, role := range roles {
		if role == controlplane {
			return true
		}
	}
	return false
}

func getInspectCmdOutput(node config.NodeInfo, cmd check.Command) ([]byte, error) {
	path, err := expandPath(node.SSHKeyPath)
	if err != nil {
		return nil, err
	}

	pubKey, err := parsePublicKey(path)
	if err != nil {
		return nil, err
	}

	khPath, err := expandPath(knownHostsFile)
	if err != nil {
		return nil, err
	}

	hostKeyCallback, err := kh.New(khPath)
	if err != nil {
		return nil, err
	}

	config := &ssh.ClientConfig{
		User:            node.User,
		Auth:            []ssh.AuthMethod{pubKey},
		HostKeyCallback: hostKeyCallback,
	}

	conn, err := ssh.Dial("tcp", node.Address+":"+node.Port, config)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	out, err := runCommand(fmt.Sprintf("docker inspect %s --format {{.Args}}", cmd), conn)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func expandPath(path string) (string, error) {
	if len(path) == 0 || path[0] != '~' {
		return path, nil
	}

	usr, err := user.Current()
	if err != nil {
		return "", err
	}
	return filepath.Join(usr.HomeDir, path[1:]), nil
}

func parsePublicKey(path string) (ssh.AuthMethod, error) {
	key, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		return nil, err
	}
	return ssh.PublicKeys(signer), nil
}

func runCommand(cmd string, conn *ssh.Client) ([]byte, error) {
	sess, err := conn.NewSession()
	if err != nil {
		return nil, err
	}
	defer sess.Close()
	out, err := sess.Output(cmd)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// btos converts slice of bytes to slice of strings split by white space characters.
func btos(in []byte) []string {
	var out []string
	for _, b := range bytes.Fields(in) {
		out = append(out, string(b))
	}
	return out
}