-
Notifications
You must be signed in to change notification settings - Fork 11
/
gssapi.go
361 lines (314 loc) · 8.97 KB
/
gssapi.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// +build kerberos
package gosasl
import (
"encoding/binary"
"encoding/json"
"fmt"
"log"
"os"
"sync"
"github.com/beltran/gssapi"
)
// GSSAPIMechanism corresponds to GSSAPI SASL mechanism
type GSSAPIMechanism struct {
config *MechanismConfig
host string
user string
service string
negotiationStage int
context *GSSAPIContext
qop byte
supportedQop uint8
serverMaxLength int
UserSelectQop uint8
MaxLength int
}
// NewGSSAPIMechanism returns a new GSSAPIMechanism
func NewGSSAPIMechanism(service string) (mechanism *GSSAPIMechanism, err error) {
context := newGSSAPIContext()
mechanism = &GSSAPIMechanism{
config: newDefaultConfig("GSSAPI"),
service: service,
negotiationStage: 0,
context: context,
supportedQop: QOP_TO_FLAG[AUTH] | QOP_TO_FLAG[AUTH_CONF] | QOP_TO_FLAG[AUTH_INT],
MaxLength: DEFAULT_MAX_LENGTH,
UserSelectQop: QOP_TO_FLAG[AUTH] | QOP_TO_FLAG[AUTH_INT] | QOP_TO_FLAG[AUTH_CONF],
}
return
}
func (m *GSSAPIMechanism) start() ([]byte, error) {
return m.step(nil)
}
func (m *GSSAPIMechanism) step(challenge []byte) ([]byte, error) {
var serviceHostQualified string
var fullServiceName string
// Allows to use a service principal designated for another host to still be used.
// Useful for containerized environments.
serviceHostQualified = os.Getenv("SERVICE_HOST_QUALIFIED")
if len(serviceHostQualified) > 0 {
fullServiceName = m.service + "/" + serviceHostQualified
} else {
fullServiceName = m.service + "/" + m.host
}
if m.negotiationStage == 0 {
err := initClientContext(m.context, fullServiceName, nil)
if err == gssapi.ErrContinueNeeded {
err = nil
}
m.negotiationStage = 1
return m.context.token, err
} else if m.negotiationStage == 1 {
err := initClientContext(m.context, fullServiceName, challenge)
if err != nil && err != gssapi.ErrContinueNeeded {
return nil, err
}
var srcName *gssapi.Name
if m.context.contextId != nil {
srcName, _, _, _, _, _, _, _ = m.context.contextId.InquireContext()
if srcName != nil {
m.user = srcName.String()
}
}
if m.user != "" {
// Check if the context is available. If the user has set the flags
// it will fail, although at this point we could know that the negotiation won't succeed
if !m.context.integAvail() && !m.context.confAvail() {
log.Println("No security layer can be established, authentication is still possible")
}
m.negotiationStage = 2
}
return m.context.token, nil
} else if m.negotiationStage == 2 {
data, err := m.context.unwrap(challenge)
if err != nil {
return nil, err
}
if len(data) != 4 {
return nil, fmt.Errorf("Decoded data should have length for at this stage")
}
qopBits := data[0]
data[0] = 0
m.serverMaxLength = int(binary.BigEndian.Uint32(data))
m.qop, err = m.selectQop(qopBits)
// The client doesn't support or want any of the security layers offered by the server
if err != nil {
m.MaxLength = 0
}
header := make([]byte, 4)
maxLength := m.serverMaxLength
if m.MaxLength < m.serverMaxLength {
maxLength = m.MaxLength
}
headerInt := (uint(m.qop) << 24) | uint(maxLength)
binary.BigEndian.PutUint32(header, uint32(headerInt))
// FLAG_BYTE + 3 bytes of length + user or authority
var name string
if name = m.user; m.config.AuthorizationID != "" {
name = m.config.AuthorizationID
}
out := append(header, []byte(name)...)
wrappedOut, err := m.context.wrap(out, false)
m.config.complete = true
return wrappedOut, err
}
return nil, fmt.Errorf("Error, this code should be unreachable")
}
func (m *GSSAPIMechanism) selectQop(qopByte byte) (byte, error) {
availableQops := m.UserSelectQop & m.supportedQop & qopByte
for _, qop := range []byte{QOP_TO_FLAG[AUTH_CONF], QOP_TO_FLAG[AUTH_INT], QOP_TO_FLAG[AUTH]} {
if qop&availableQops != 0 {
return qop, nil
}
}
return byte(0), fmt.Errorf("No qop satisfying all the conditions where found")
}
// replaceSPNHostWildcard substitutes the special string '_HOST' in the given
// SPN for the given (current) host.
func replaceSPNHostWildcard(spn, host string) string {
res := krbSPNHost.FindStringSubmatchIndex(spn)
if res == nil || res[2] == -1 {
return spn
}
return spn[:res[2]] + host + spn[res[3]:]
}
func (m GSSAPIMechanism) encode(outgoing []byte) ([]byte, error) {
if m.qop == QOP_TO_FLAG[AUTH] {
return outgoing, nil
} else {
var conf_flag bool = false
if m.qop == QOP_TO_FLAG[AUTH_CONF] {
conf_flag = true
}
return m.context.wrap(deepCopy(outgoing), conf_flag)
}
}
func (m GSSAPIMechanism) decode(incoming []byte) ([]byte, error) {
if m.qop == QOP_TO_FLAG[AUTH] {
return incoming, nil
}
return m.context.unwrap(deepCopy(incoming))
}
func deepCopy(original []byte) []byte {
copied := make([]byte, len(original))
for i, el := range original {
copied[i] = el
}
return copied
}
func (m GSSAPIMechanism) dispose() {
m.context.dispose()
}
func (m GSSAPIMechanism) getConfig() *MechanismConfig {
return m.config
}
type GSSAPIContext struct {
DebugLog bool
RunAsService bool
ServiceName string
ServiceAddress string
gssapi.Options
*gssapi.Lib `json:"-"`
loadonce sync.Once
// Service credentials loaded from keytab
credential *gssapi.CredId
token []byte
continueNeeded bool
contextId *gssapi.CtxId
reqFlags uint32
availFlags uint32
}
//
func newGSSAPIContext() *GSSAPIContext {
var c = &GSSAPIContext{
reqFlags: uint32(gssapi.GSS_C_INTEG_FLAG) + uint32(gssapi.GSS_C_MUTUAL_FLAG) + uint32(gssapi.GSS_C_SEQUENCE_FLAG) + uint32(gssapi.GSS_C_CONF_FLAG),
}
prefix := "gosasl-client"
err := loadlib(c.DebugLog, prefix, c)
if err != nil {
log.Fatal(err)
}
j, _ := json.MarshalIndent(c, "", " ")
c.Debug(fmt.Sprintf("Config: %s", string(j)))
return c
}
// InitClientContext initializes the context and gets the response(token)
// to send to the server
func initClientContext(c *GSSAPIContext, service string, inputToken []byte) error {
c.ServiceName = service
var _inputToken *gssapi.Buffer
var err error
if inputToken == nil {
_inputToken = c.GSS_C_NO_BUFFER
} else {
_inputToken, err = c.MakeBufferBytes(inputToken)
defer _inputToken.Release()
if err != nil {
return err
}
}
preparedName := prepareServiceName(c)
defer preparedName.Release()
// Error is purposedly ignored.
contextId, _, token, outputRetFlags, _, err := c.InitSecContext(
nil,
c.contextId,
preparedName,
c.GSS_MECH_KRB5,
c.reqFlags,
0,
c.GSS_C_NO_CHANNEL_BINDINGS,
_inputToken)
defer token.Release()
c.token = token.Bytes()
c.contextId = contextId
c.availFlags = outputRetFlags
return err
}
// Wrap calls GSS_Wrap
func (c *GSSAPIContext) wrap(original []byte, conf_flag bool) (wrapped []byte, err error) {
if original == nil {
return
}
_original, err := c.MakeBufferBytes(original)
defer _original.Release()
if err != nil {
return nil, err
}
_, wrappedBuffer, err := c.contextId.Wrap(conf_flag, gssapi.GSS_C_QOP_DEFAULT, _original)
defer wrappedBuffer.Release()
if err != nil {
return nil, err
}
return wrappedBuffer.Bytes(), nil
}
// Unwrap calls GSS_Unwrap
func (c *GSSAPIContext) unwrap(original []byte) (unwrapped []byte, err error) {
if original == nil {
return
}
_original, err := c.MakeBufferBytes(original)
defer _original.Release()
if err != nil {
return nil, err
}
unwrappedBuffer, _, _, err := c.contextId.Unwrap(_original)
defer unwrappedBuffer.Release()
if err != nil {
return nil, err
}
return unwrappedBuffer.Bytes(), nil
}
// Dispose releases the acquired memory and destroys sensitive information
func (c *GSSAPIContext) dispose() error {
if c.contextId != nil {
return c.contextId.Unload()
}
return nil
}
// IntegAvail returns true in the integ_flag is available and therefore a security layer can be established
func (c *GSSAPIContext) integAvail() bool {
return c.availFlags&uint32(gssapi.GSS_C_INTEG_FLAG) != 0
}
// ConfAvail returns true in the conf_flag is available and therefore a confidentiality layer can be established
func (c *GSSAPIContext) confAvail() bool {
return c.availFlags&uint32(gssapi.GSS_C_CONF_FLAG) != 0
}
func loadlib(debug bool, prefix string, c *GSSAPIContext) error {
max := gssapi.Err + 1
if debug {
max = gssapi.MaxSeverity
}
pp := make([]gssapi.Printer, 0, max)
for i := gssapi.Severity(0); i < max; i++ {
p := log.New(os.Stderr,
fmt.Sprintf("%s: %s\t", prefix, i),
log.LstdFlags)
pp = append(pp, p)
}
c.Options.Printers = pp
lib, err := gssapi.Load(&c.Options)
if err != nil {
return err
}
c.Lib = lib
return nil
}
func prepareServiceName(c *GSSAPIContext) *gssapi.Name {
if c.ServiceName == "" {
log.Fatal("Need a --service-name")
}
nameBuf, err := c.MakeBufferString(c.ServiceName)
defer nameBuf.Release()
if err != nil {
log.Fatal(err)
}
name, err := nameBuf.Name(c.GSS_KRB5_NT_PRINCIPAL_NAME)
if err != nil {
log.Fatal(err)
}
if name.String() != c.ServiceName {
log.Fatalf("name: got %q, expected %q", name.String(), c.ServiceName)
}
return name
}