forked from spiffe/spire
/
psat.go
290 lines (238 loc) · 8.86 KB
/
psat.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
package k8spsat
import (
"context"
"encoding/json"
"fmt"
"sync"
nodeattestorv1 "github.com/accuknox/spire-plugin-sdk/proto/spire/plugin/server/nodeattestor/v1"
configv1 "github.com/accuknox/spire-plugin-sdk/proto/spire/service/common/config/v1"
"github.com/accuknox/spire/pkg/common/catalog"
"github.com/accuknox/spire/pkg/common/plugin/k8s"
"github.com/accuknox/spire/pkg/common/plugin/k8s/apiserver"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/hcl"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
// Add auth providers to authenticate to clusters to verify tokens
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
const (
pluginName = "k8s_psat"
)
var (
defaultAudience = []string{"spire-server"}
)
func BuiltIn() catalog.BuiltIn {
return builtin(New())
}
func builtin(p *AttestorPlugin) catalog.BuiltIn {
return catalog.MakeBuiltIn(pluginName,
nodeattestorv1.NodeAttestorPluginServer(p),
configv1.ConfigServiceServer(p),
)
}
// AttestorConfig contains a map of clusters that uses cluster name as key
type AttestorConfig struct {
Clusters map[string]*ClusterConfig `hcl:"clusters"`
}
// ClusterConfig holds a single cluster configuration
type ClusterConfig struct {
// Array of allowed service accounts names
// Attestation is denied if coming from a service account that is not in the list
ServiceAccountAllowList []string `hcl:"service_account_allow_list"`
// Audience for PSAT token validation
// If audience is not configured, defaultAudience will be used
// If audience value is set to an empty slice, k8s apiserver audience will be used
Audience *[]string `hcl:"audience"`
// Kubernetes configuration file path
// Used to create a k8s client to query the API server. If string is empty, in-cluster configuration is used
KubeConfigFile string `hcl:"kube_config_file"`
// Node labels that are allowed to use as selectors
AllowedNodeLabelKeys []string `hcl:"allowed_node_label_keys"`
// Pod labels that are allowed to use as selectors
AllowedPodLabelKeys []string `hcl:"allowed_pod_label_keys"`
}
type attestorConfig struct {
trustDomain string
clusters map[string]*clusterConfig
}
type clusterConfig struct {
serviceAccounts map[string]bool
audience []string
client apiserver.Client
allowedNodeLabelKeys map[string]bool
allowedPodLabelKeys map[string]bool
}
// AttestorPlugin is a PSAT (Projected SAT) node attestor plugin
type AttestorPlugin struct {
nodeattestorv1.UnsafeNodeAttestorServer
configv1.UnsafeConfigServer
mu sync.RWMutex
config *attestorConfig
log hclog.Logger
}
// New creates a new PSAT node attestor plugin
func New() *AttestorPlugin {
return &AttestorPlugin{}
}
var _ nodeattestorv1.NodeAttestorServer = (*AttestorPlugin)(nil)
// SetLogger sets up plugin logging
func (p *AttestorPlugin) SetLogger(log hclog.Logger) {
p.log = log
}
func (p *AttestorPlugin) Attest(stream nodeattestorv1.NodeAttestor_AttestServer) error {
req, err := stream.Recv()
if err != nil {
return err
}
config, err := p.getConfig()
if err != nil {
return err
}
payload := req.GetPayload()
if payload == nil {
return status.Error(codes.InvalidArgument, "missing attestation payload")
}
attestationData := new(k8s.PSATAttestationData)
if err := json.Unmarshal(payload, attestationData); err != nil {
return status.Errorf(codes.InvalidArgument, "failed to unmarshal data payload: %v", err)
}
if attestationData.Cluster == "" {
return status.Error(codes.InvalidArgument, "missing cluster in attestation data")
}
if attestationData.Token == "" {
return status.Error(codes.InvalidArgument, "missing token in attestation data")
}
cluster := config.clusters[attestationData.Cluster]
if cluster == nil {
return status.Errorf(codes.InvalidArgument, "not configured for cluster %q", attestationData.Cluster)
}
tokenStatus, err := cluster.client.ValidateToken(stream.Context(), attestationData.Token, cluster.audience)
if err != nil {
return status.Errorf(codes.Internal, "unable to validate token with TokenReview API: %v", err)
}
if !tokenStatus.Authenticated {
return status.Error(codes.PermissionDenied, "token not authenticated according to TokenReview API")
}
namespace, serviceAccountName, err := k8s.GetNamesFromTokenStatus(tokenStatus)
if err != nil {
return status.Errorf(codes.Internal, "fail to parse username from token review status: %v", err)
}
fullServiceAccountName := fmt.Sprintf("%v:%v", namespace, serviceAccountName)
if !cluster.serviceAccounts[fullServiceAccountName] {
return status.Errorf(codes.PermissionDenied, "%q is not an allowed service account", fullServiceAccountName)
}
podName, err := k8s.GetPodNameFromTokenStatus(tokenStatus)
if err != nil {
return status.Errorf(codes.Internal, "fail to get pod name from token review status: %v", err)
}
podUID, err := k8s.GetPodUIDFromTokenStatus(tokenStatus)
if err != nil {
return status.Errorf(codes.Internal, "fail to get pod UID from token review status: %v", err)
}
pod, err := cluster.client.GetPod(stream.Context(), namespace, podName)
if err != nil {
return status.Errorf(codes.Internal, "fail to get pod from k8s API server: %v", err)
}
node, err := cluster.client.GetNode(stream.Context(), pod.Spec.NodeName)
if err != nil {
return status.Errorf(codes.Internal, "fail to get node from k8s API server: %v", err)
}
nodeUID := string(node.UID)
if nodeUID == "" {
return status.Errorf(codes.Internal, "node UID is empty")
}
selectorValues := []string{
k8s.MakeSelectorValue("cluster", attestationData.Cluster),
k8s.MakeSelectorValue("agent_ns", namespace),
k8s.MakeSelectorValue("agent_sa", serviceAccountName),
k8s.MakeSelectorValue("agent_pod_name", podName),
k8s.MakeSelectorValue("agent_pod_uid", podUID),
k8s.MakeSelectorValue("agent_node_ip", pod.Status.HostIP),
k8s.MakeSelectorValue("agent_node_name", pod.Spec.NodeName),
k8s.MakeSelectorValue("agent_node_uid", nodeUID),
}
for key, value := range node.Labels {
if cluster.allowedNodeLabelKeys[key] {
selectorValues = append(selectorValues, k8s.MakeSelectorValue("agent_node_label", key, value))
}
}
for key, value := range pod.Labels {
if cluster.allowedPodLabelKeys[key] {
selectorValues = append(selectorValues, k8s.MakeSelectorValue("agent_pod_label", key, value))
}
}
return stream.Send(&nodeattestorv1.AttestResponse{
Response: &nodeattestorv1.AttestResponse_AgentAttributes{
AgentAttributes: &nodeattestorv1.AgentAttributes{
CanReattest: true,
SpiffeId: k8s.AgentID(pluginName, config.trustDomain, attestationData.Cluster, nodeUID),
SelectorValues: selectorValues,
},
},
})
}
func (p *AttestorPlugin) Configure(ctx context.Context, req *configv1.ConfigureRequest) (*configv1.ConfigureResponse, error) {
hclConfig := new(AttestorConfig)
if err := hcl.Decode(hclConfig, req.HclConfiguration); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "unable to decode configuration: %v", err)
}
if req.CoreConfiguration == nil {
return nil, status.Error(codes.InvalidArgument, "core configuration is required")
}
if req.CoreConfiguration.TrustDomain == "" {
return nil, status.Error(codes.InvalidArgument, "core configuration missing trust domain")
}
if len(hclConfig.Clusters) == 0 {
return nil, status.Error(codes.InvalidArgument, "configuration must have at least one cluster")
}
config := &attestorConfig{
trustDomain: req.CoreConfiguration.TrustDomain,
clusters: make(map[string]*clusterConfig),
}
for name, cluster := range hclConfig.Clusters {
if len(cluster.ServiceAccountAllowList) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "cluster %q configuration must have at least one service account allowed", name)
}
serviceAccounts := make(map[string]bool)
for _, serviceAccount := range cluster.ServiceAccountAllowList {
serviceAccounts[serviceAccount] = true
}
var audience []string
if cluster.Audience == nil {
audience = defaultAudience
} else {
audience = *cluster.Audience
}
allowedNodeLabelKeys := make(map[string]bool)
for _, label := range cluster.AllowedNodeLabelKeys {
allowedNodeLabelKeys[label] = true
}
allowedPodLabelKeys := make(map[string]bool)
for _, label := range cluster.AllowedPodLabelKeys {
allowedPodLabelKeys[label] = true
}
config.clusters[name] = &clusterConfig{
serviceAccounts: serviceAccounts,
audience: audience,
client: apiserver.New(cluster.KubeConfigFile),
allowedNodeLabelKeys: allowedNodeLabelKeys,
allowedPodLabelKeys: allowedPodLabelKeys,
}
}
p.setConfig(config)
return &configv1.ConfigureResponse{}, nil
}
func (p *AttestorPlugin) getConfig() (*attestorConfig, error) {
p.mu.RLock()
defer p.mu.RUnlock()
if p.config == nil {
return nil, status.Error(codes.FailedPrecondition, "not configured")
}
return p.config, nil
}
func (p *AttestorPlugin) setConfig(config *attestorConfig) {
p.mu.Lock()
defer p.mu.Unlock()
p.config = config
}