-
Notifications
You must be signed in to change notification settings - Fork 52
/
challenge.go
292 lines (244 loc) · 7.38 KB
/
challenge.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
291
292
package session
import (
"context"
"crypto/subtle"
corev1 "github.com/rancher/opni/pkg/apis/core/v1"
authutil "github.com/rancher/opni/pkg/auth/util"
"github.com/rancher/opni/pkg/util/streams"
"golang.org/x/crypto/blake2b"
"github.com/rancher/opni/pkg/auth/cluster"
"github.com/rancher/opni/pkg/keyring"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
DomainString = "session auth v1"
)
type ServerChallenge struct {
ServerChallengeOptions
attrLoader
}
type ServerChallengeOptions struct {
attributeRequestLimit int
}
type ServerChallengeOption func(*ServerChallengeOptions)
func (o *ServerChallengeOptions) apply(opts ...ServerChallengeOption) {
for _, op := range opts {
op(o)
}
}
func WithAttributeRequestLimit(attributeRequestLimit int) ServerChallengeOption {
return func(o *ServerChallengeOptions) {
o.attributeRequestLimit = attributeRequestLimit
}
}
func NewServerChallenge(kr keyring.Keyring, opts ...ServerChallengeOption) (*ServerChallenge, error) {
options := ServerChallengeOptions{
attributeRequestLimit: 10,
}
options.apply(opts...)
attr, err := loadAttributes(kr)
if err != nil {
return nil, err
}
return &ServerChallenge{
ServerChallengeOptions: options,
attrLoader: attr,
}, nil
}
func (a *ServerChallenge) InterceptContext(ctx context.Context) context.Context {
return ctx
}
func (a *ServerChallenge) DoChallenge(ss streams.Stream) (context.Context, error) {
challengeRequests := corev1.ChallengeRequestList{}
var reqAttributes []SecretAttribute
id := cluster.StreamAuthorizedID(ss.Context())
sharedKeys := cluster.StreamAuthorizedKeys(ss.Context())
md, ok := metadata.FromIncomingContext(ss.Context())
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "metadata not found in context")
}
attrRequests := md.Get(AttributeMetadataKey)
if len(attrRequests) > a.attributeRequestLimit {
return nil, status.Errorf(codes.InvalidArgument, "number of attribute requests exceeds limit")
}
for _, v := range attrRequests {
if attr, ok := a.attributesByName[v]; ok {
cr := &corev1.ChallengeRequest{
Challenge: authutil.NewRandom256(),
}
challengeRequests.Items = append(challengeRequests.Items, cr)
reqAttributes = append(reqAttributes, attr)
} else {
return nil, status.Errorf(codes.InvalidArgument, "unknown/unsupported session attribute: %s", v)
}
}
if err := ss.SendMsg(&challengeRequests); err != nil {
return nil, err
}
challengeResponses := corev1.ChallengeResponseList{}
if err := ss.RecvMsg(&challengeResponses); err != nil {
return nil, err
}
if len(challengeResponses.Items) != len(challengeRequests.Items) {
return nil, status.Errorf(codes.InvalidArgument, "invalid number of challenge responses")
}
var failed bool
for i, challengeResponse := range challengeResponses.Items {
challengeRequest := challengeRequests.Items[i]
attr := reqAttributes[i]
ok := attr.Verify(id, challengeRequest.Challenge, challengeResponse.Response)
if !ok {
failed = true
}
}
if failed {
return nil, status.Errorf(codes.Unauthenticated, "session attribute verification failed")
}
sessionInfo := &corev1.SessionInfo{}
{
// compute a mac over the id, challenge requests, and responses
mac, _ := blake2b.New512(sharedKeys.ServerKey)
mac.Write([]byte(id))
for _, cr := range challengeRequests.Items {
mac.Write(cr.Challenge)
}
for _, cr := range challengeResponses.Items {
mac.Write(cr.Response)
}
for _, attr := range reqAttributes {
mac.Write([]byte(attr.Name()))
sessionInfo.Attributes = append(sessionInfo.Attributes, attr.Name())
}
sessionInfo.Mac = mac.Sum(nil)
}
if err := ss.SendMsg(sessionInfo); err != nil {
return nil, err
}
ctx := context.WithValue(ss.Context(), AttributesKey, reqAttributes)
return ctx, nil
}
type ClientChallenge struct {
attrLoader
}
func NewClientChallenge(kr keyring.Keyring) (*ClientChallenge, error) {
attr, err := loadAttributes(kr)
if err != nil {
return nil, err
}
return &ClientChallenge{
attrLoader: attr,
}, nil
}
func (a *ClientChallenge) InterceptContext(ctx context.Context) context.Context {
if len(a.attributes) == 0 {
return ctx
}
kvs := make([]string, 0, len(a.attributes)*2)
for _, attr := range a.attributes {
kvs = append(kvs, AttributeMetadataKey, attr.Name())
}
return metadata.AppendToOutgoingContext(ctx, kvs...)
}
func (a *ClientChallenge) DoChallenge(cs streams.Stream) (context.Context, error) {
id := cluster.StreamAuthorizedID(cs.Context())
sharedKeys := cluster.StreamAuthorizedKeys(cs.Context())
var challengeRequests corev1.ChallengeRequestList
if err := cs.RecvMsg(&challengeRequests); err != nil {
return nil, err
}
if len(challengeRequests.Items) != len(a.attributes) {
return nil, status.Errorf(codes.Internal, "server sent the wrong number of challenge requests")
}
challengeResponses := corev1.ChallengeResponseList{
Items: make([]*corev1.ChallengeResponse, len(challengeRequests.Items)),
}
for i, challenge := range challengeRequests.Items {
attr := a.attributes[i]
mac := attr.Solve(id, challenge.Challenge)
challengeResponses.Items[i] = &corev1.ChallengeResponse{
Response: mac,
}
}
if err := cs.SendMsg(&challengeResponses); err != nil {
return nil, status.Errorf(codes.Aborted, "error sending challenge response: %v", err)
}
var sessionInfo corev1.SessionInfo
if err := cs.RecvMsg(&sessionInfo); err != nil {
return nil, err
}
// verify the mac
{
mac, _ := blake2b.New512(sharedKeys.ServerKey)
mac.Write([]byte(id))
for _, cr := range challengeRequests.Items {
mac.Write(cr.Challenge)
}
for _, cr := range challengeResponses.Items {
mac.Write(cr.Response)
}
for _, attr := range a.attributes {
mac.Write([]byte(attr.Name()))
}
expectedMac := mac.Sum(nil)
if subtle.ConstantTimeCompare(expectedMac, sessionInfo.Mac) != 1 {
return nil, status.Errorf(codes.Aborted, "session info verification failed")
}
}
ctx := context.WithValue(cs.Context(), AttributesKey, a.attributes)
return ctx, nil
}
type attrLoader struct {
attributes []SecretAttribute
attributesByName map[string]SecretAttribute
}
func (a *attrLoader) Attributes() []string {
var names []string
for _, attr := range a.attributes {
names = append(names, attr.Name())
}
return names
}
// Matches challenges.ConditionFunc
func (a *attrLoader) HasAttributes(_ context.Context) (bool, error) {
return len(a.attributes) > 0, nil
}
func loadAttributes(kr keyring.Keyring) (_ attrLoader, err error) {
var attrs []SecretAttribute
kr.Try(func(ek *keyring.EphemeralKey) {
if err != nil {
return
}
if v, ok := ek.Labels[AttributeLabelKey]; ok {
var attr SecretAttribute
attr, err = NewSecretAttribute(v, ek.Secret)
if err != nil {
return
}
attrs = append(attrs, attr)
}
})
if err != nil {
return
}
attributesByName := map[string]SecretAttribute{}
for _, attr := range attrs {
attributesByName[attr.Name()] = attr
}
return attrLoader{
attributes: attrs,
attributesByName: attributesByName,
}, nil
}
// Checks if the incoming context has the session attribute metadata key.
// Can be used in conjunction with a conditional challenge handler on the
// server side.
func ShouldEnableIncoming(streamContext context.Context) (bool, error) {
if md, ok := metadata.FromIncomingContext(streamContext); ok {
if v := md.Get(AttributeMetadataKey); len(v) > 0 {
return true, nil
}
}
return false, nil
}