cleanup, refactor TLV code
[mech_eap.git] / accept_sec_context.c
1 /*
2  * Copyright (c) 2011, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * Establish a security context on the acceptor (server). These functions
35  * wrap around libradsec and (thus) talk to a RADIUS server or proxy.
36  */
37
38 #include "gssapiP_eap.h"
39
40 #ifdef GSSEAP_ENABLE_REAUTH
41 static OM_uint32
42 eapGssSmAcceptGssReauth(OM_uint32 *minor,
43                         gss_cred_id_t cred,
44                         gss_ctx_id_t ctx,
45                         gss_name_t target __attribute__((__unused__)),
46                         gss_OID mech __attribute__((__unused__)),
47                         OM_uint32 reqFlags __attribute__((__unused__)),
48                         OM_uint32 timeReq __attribute__((__unused__)),
49                         gss_channel_bindings_t chanBindings,
50                         gss_buffer_t inputToken,
51                         gss_buffer_t outputToken,
52                         OM_uint32 *smFlags);
53 #endif
54
55 /*
56  * Mark an acceptor context as ready for cryptographic operations
57  */
58 static OM_uint32
59 acceptReadyEap(OM_uint32 *minor, gss_ctx_id_t ctx, gss_cred_id_t cred)
60 {
61     OM_uint32 major, tmpMinor;
62     VALUE_PAIR *vp;
63     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
64
65     /* Cache encryption type derived from selected mechanism OID */
66     major = gssEapOidToEnctype(minor, ctx->mechanismUsed,
67                                &ctx->encryptionType);
68     if (GSS_ERROR(major))
69         return major;
70
71     gssEapReleaseName(&tmpMinor, &ctx->initiatorName);
72
73     major = gssEapRadiusGetRawAvp(minor, ctx->acceptorCtx.vps,
74                                   PW_USER_NAME, 0, &vp);
75     if (major == GSS_S_COMPLETE) {
76         nameBuf.length = vp->length;
77         nameBuf.value = vp->vp_strvalue;
78     } else {
79         ctx->gssFlags |= GSS_C_ANON_FLAG;
80     }
81
82     major = gssEapImportName(minor, &nameBuf,
83                              (ctx->gssFlags & GSS_C_ANON_FLAG) ?
84                                 GSS_C_NT_ANONYMOUS : GSS_C_NT_USER_NAME,
85                              &ctx->initiatorName);
86     if (GSS_ERROR(major))
87         return major;
88
89     major = gssEapRadiusGetRawAvp(minor, ctx->acceptorCtx.vps,
90                                   PW_MS_MPPE_SEND_KEY, VENDORPEC_MS, &vp);
91     if (GSS_ERROR(major)) {
92         *minor = GSSEAP_KEY_UNAVAILABLE;
93         return GSS_S_UNAVAILABLE;
94     }
95
96     major = gssEapDeriveRfc3961Key(minor,
97                                    vp->vp_octets,
98                                    vp->length,
99                                    ctx->encryptionType,
100                                    &ctx->rfc3961Key);
101     if (GSS_ERROR(major))
102         return major;
103
104     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
105                                        &ctx->checksumType);
106     if (GSS_ERROR(major))
107         return major;
108
109     major = sequenceInit(minor,
110                          &ctx->seqState, ctx->recvSeq,
111                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
112                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
113                          TRUE);
114     if (GSS_ERROR(major))
115         return major;
116
117     major = gssEapCreateAttrContext(minor, cred, ctx,
118                                     &ctx->initiatorName->attrCtx,
119                                     &ctx->expiryTime);
120     if (GSS_ERROR(major))
121         return major;
122
123     *minor = 0;
124     return GSS_S_COMPLETE;
125 }
126
127 /*
128  * Emit a identity EAP request to force the initiator (peer) to identify
129  * itself.
130  */
131 static OM_uint32
132 eapGssSmAcceptIdentity(OM_uint32 *minor,
133                        gss_cred_id_t cred,
134                        gss_ctx_id_t ctx,
135                        gss_name_t target __attribute__((__unused__)),
136                        gss_OID mech __attribute__((__unused__)),
137                        OM_uint32 reqFlags __attribute__((__unused__)),
138                        OM_uint32 timeReq __attribute__((__unused__)),
139                        gss_channel_bindings_t chanBindings __attribute__((__unused__)),
140                        gss_buffer_t inputToken,
141                        gss_buffer_t outputToken,
142                        OM_uint32 *smFlags)
143 {
144     OM_uint32 major;
145     struct wpabuf *reqData;
146     gss_buffer_desc pktBuffer;
147
148     if (!gssEapCredAvailable(cred, ctx->mechanismUsed)) {
149         *minor = GSSEAP_CRED_MECH_MISMATCH;
150         return GSS_S_BAD_MECH;
151     }
152
153     if (inputToken != GSS_C_NO_BUFFER && inputToken->length != 0) {
154         *minor = GSSEAP_WRONG_SIZE;
155         return GSS_S_DEFECTIVE_TOKEN;
156     }
157
158     assert(ctx->acceptorName == GSS_C_NO_NAME);
159
160     if (cred->name != GSS_C_NO_NAME) {
161         major = gssEapDuplicateName(minor, cred->name, &ctx->acceptorName);
162         if (GSS_ERROR(major))
163             return major;
164     }
165
166     reqData = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_IDENTITY, 0,
167                             EAP_CODE_REQUEST, 0);
168     if (reqData == NULL) {
169         *minor = ENOMEM;
170         return GSS_S_FAILURE;
171     }
172
173     pktBuffer.length = wpabuf_len(reqData);
174     pktBuffer.value = (void *)wpabuf_head(reqData);
175
176     major = duplicateBuffer(minor, &pktBuffer, outputToken);
177     if (GSS_ERROR(major))
178         return major;
179
180     wpabuf_free(reqData);
181
182     *minor = 0;
183     *smFlags |= SM_FLAG_TRANSITION;
184
185     return GSS_S_CONTINUE_NEEDED;
186 }
187
188 /*
189  * Returns TRUE if the input token contains an EAP identity response.
190  */
191 static int
192 isIdentityResponseP(gss_buffer_t inputToken)
193 {
194     struct wpabuf respData;
195
196     wpabuf_set(&respData, inputToken->value, inputToken->length);
197
198     return (eap_get_type(&respData) == EAP_TYPE_IDENTITY);
199 }
200
201 /*
202  * Save the asserted initiator identity from the EAP identity response.
203  */
204 static OM_uint32
205 importInitiatorIdentity(OM_uint32 *minor,
206                         gss_ctx_id_t ctx,
207                         gss_buffer_t inputToken)
208 {
209     OM_uint32 tmpMinor;
210     struct wpabuf respData;
211     const unsigned char *pos;
212     size_t len;
213     gss_buffer_desc nameBuf;
214
215     wpabuf_set(&respData, inputToken->value, inputToken->length);
216
217     pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_IDENTITY,
218                            &respData, &len);
219     if (pos == NULL) {
220         *minor = GSSEAP_PEER_BAD_MESSAGE;
221         return GSS_S_DEFECTIVE_TOKEN;
222     }
223
224     nameBuf.value = (void *)pos;
225     nameBuf.length = len;
226
227     gssEapReleaseName(&tmpMinor, &ctx->initiatorName);
228
229     return gssEapImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
230                             &ctx->initiatorName);
231 }
232
233 /*
234  * Pass the asserted initiator identity to the authentication server.
235  */
236 static OM_uint32
237 setInitiatorIdentity(OM_uint32 *minor,
238                      gss_ctx_id_t ctx,
239                      VALUE_PAIR **vps)
240 {
241     OM_uint32 major, tmpMinor;
242     gss_buffer_desc nameBuf;
243
244     /*
245      * We should have got an EAP identity response, but if we didn't, then
246      * we will just avoid sending User-Name. Note that radsecproxy requires
247      * User-Name to be sent on every request (presumably so it can remain
248      * stateless).
249      */
250     if (ctx->initiatorName != GSS_C_NO_NAME) {
251         major = gssEapDisplayName(minor, ctx->initiatorName, &nameBuf, NULL);
252         if (GSS_ERROR(major))
253             return major;
254
255         major = gssEapRadiusAddAvp(minor, vps, PW_USER_NAME, 0, &nameBuf);
256         if (GSS_ERROR(major))
257             return major;
258
259         gss_release_buffer(&tmpMinor, &nameBuf);
260     }
261
262     *minor = 0;
263     return GSS_S_COMPLETE;
264 }
265
266 /*
267  * Pass the asserted acceptor identity to the authentication server.
268  */
269 static OM_uint32
270 setAcceptorIdentity(OM_uint32 *minor,
271                     gss_ctx_id_t ctx,
272                     VALUE_PAIR **vps)
273 {
274     OM_uint32 major;
275     gss_buffer_desc nameBuf;
276     krb5_context krbContext = NULL;
277     krb5_principal krbPrinc;
278     struct rs_context *rc = ctx->acceptorCtx.radContext;
279
280     assert(rc != NULL);
281
282     if (ctx->acceptorName == GSS_C_NO_NAME) {
283         *minor = 0;
284         return GSS_S_COMPLETE;
285     }
286
287     if ((ctx->acceptorName->flags & NAME_FLAG_SERVICE) == 0) {
288         *minor = GSSEAP_BAD_SERVICE_NAME;
289         return GSS_S_BAD_NAME;
290     }
291
292     GSSEAP_KRB_INIT(&krbContext);
293
294     krbPrinc = ctx->acceptorName->krbPrincipal;
295     assert(krbPrinc != NULL);
296     assert(KRB_PRINC_LENGTH(krbPrinc) >= 2);
297
298     /* Acceptor-Service-Name */
299     krbPrincComponentToGssBuffer(krbPrinc, 0, &nameBuf);
300
301     major = gssEapRadiusAddAvp(minor, vps,
302                                PW_GSS_ACCEPTOR_SERVICE_NAME,
303                                VENDORPEC_UKERNA,
304                                &nameBuf);
305     if (GSS_ERROR(major))
306         return major;
307
308     /* Acceptor-Host-Name */
309     krbPrincComponentToGssBuffer(krbPrinc, 1, &nameBuf);
310
311     major = gssEapRadiusAddAvp(minor, vps,
312                                PW_GSS_ACCEPTOR_HOST_NAME,
313                                VENDORPEC_UKERNA,
314                                &nameBuf);
315     if (GSS_ERROR(major))
316         return major;
317
318     if (KRB_PRINC_LENGTH(krbPrinc) > 2) {
319         /* Acceptor-Service-Specific */
320         krb5_principal_data ssiPrinc = *krbPrinc;
321         char *ssi;
322
323         KRB_PRINC_LENGTH(&ssiPrinc) -= 2;
324         KRB_PRINC_NAME(&ssiPrinc) += 2;
325
326         *minor = krb5_unparse_name_flags(krbContext, &ssiPrinc,
327                                          KRB5_PRINCIPAL_UNPARSE_NO_REALM, &ssi);
328         if (*minor != 0)
329             return GSS_S_FAILURE;
330
331         nameBuf.value = ssi;
332         nameBuf.length = strlen(ssi);
333
334         major = gssEapRadiusAddAvp(minor, vps,
335                                    PW_GSS_ACCEPTOR_SERVICE_SPECIFIC,
336                                    VENDORPEC_UKERNA,
337                                    &nameBuf);
338
339         if (GSS_ERROR(major)) {
340             krb5_free_unparsed_name(krbContext, ssi);
341             return major;
342         }
343         krb5_free_unparsed_name(krbContext, ssi);
344     }
345
346     krbPrincRealmToGssBuffer(krbPrinc, &nameBuf);
347     if (nameBuf.length != 0) {
348         /* Acceptor-Realm-Name */
349         major = gssEapRadiusAddAvp(minor, vps,
350                                    PW_GSS_ACCEPTOR_REALM_NAME,
351                                    VENDORPEC_UKERNA,
352                                    &nameBuf);
353         if (GSS_ERROR(major))
354             return major;
355     }
356
357     *minor = 0;
358     return GSS_S_COMPLETE;
359 }
360
361 /*
362  * Allocate a RadSec handle
363  */
364 static OM_uint32
365 createRadiusHandle(OM_uint32 *minor,
366                    gss_cred_id_t cred,
367                    gss_ctx_id_t ctx)
368 {
369     struct gss_eap_acceptor_ctx *actx = &ctx->acceptorCtx;
370     const char *configFile = RS_CONFIG_FILE;
371     const char *configStanza = "gss-eap";
372     struct rs_alloc_scheme ralloc;
373     struct rs_error *err;
374
375     assert(actx->radContext == NULL);
376     assert(actx->radConn == NULL);
377
378     if (rs_context_create(&actx->radContext, RS_DICT_FILE) != 0) {
379         *minor = GSSEAP_RADSEC_CONTEXT_FAILURE;
380         return GSS_S_FAILURE;
381     }
382
383     if (cred->radiusConfigFile != NULL)
384         configFile = cred->radiusConfigFile;
385     if (cred->radiusConfigStanza != NULL)
386         configStanza = cred->radiusConfigStanza;
387
388     ralloc.calloc  = GSSEAP_CALLOC;
389     ralloc.malloc  = GSSEAP_MALLOC;
390     ralloc.free    = GSSEAP_FREE;
391     ralloc.realloc = GSSEAP_REALLOC;
392
393     rs_context_set_alloc_scheme(actx->radContext, &ralloc);
394
395     if (rs_context_read_config(actx->radContext, configFile) != 0) {
396         err = rs_err_ctx_pop(actx->radContext);
397         goto fail;
398     }
399
400     if (rs_conn_create(actx->radContext, &actx->radConn, configStanza) != 0) {
401         err = rs_err_conn_pop(actx->radConn);
402         goto fail;
403     }
404
405     if (actx->radServer != NULL) {
406         if (rs_conn_select_peer(actx->radConn, actx->radServer) != 0) {
407             err = rs_err_conn_pop(actx->radConn);
408             goto fail;
409         }
410     }
411
412     *minor = 0;
413     return GSS_S_COMPLETE;
414
415 fail:
416     return gssEapRadiusMapError(minor, err);
417 }
418
419 /*
420  * Process a EAP response from the initiator.
421  */
422 static OM_uint32
423 eapGssSmAcceptAuthenticate(OM_uint32 *minor,
424                            gss_cred_id_t cred,
425                            gss_ctx_id_t ctx,
426                            gss_name_t target __attribute__((__unused__)),
427                            gss_OID mech __attribute__((__unused__)),
428                            OM_uint32 reqFlags __attribute__((__unused__)),
429                            OM_uint32 timeReq __attribute__((__unused__)),
430                            gss_channel_bindings_t chanBindings,
431                            gss_buffer_t inputToken,
432                            gss_buffer_t outputToken,
433                            OM_uint32 *smFlags)
434 {
435     OM_uint32 major, tmpMinor;
436     struct rs_connection *rconn;
437     struct rs_request *request = NULL;
438     struct rs_packet *req = NULL, *resp = NULL;
439     struct radius_packet *frreq, *frresp;
440
441     if (ctx->acceptorCtx.radContext == NULL) {
442         /* May be NULL from an imported partial context */
443         major = createRadiusHandle(minor, cred, ctx);
444         if (GSS_ERROR(major))
445             goto cleanup;
446     }
447
448     if (isIdentityResponseP(inputToken)) {
449         major = importInitiatorIdentity(minor, ctx, inputToken);
450         if (GSS_ERROR(major))
451             return major;
452     }
453
454     rconn = ctx->acceptorCtx.radConn;
455
456     if (rs_packet_create_authn_request(rconn, &req, NULL, NULL) != 0) {
457         major = gssEapRadiusMapError(minor, rs_err_conn_pop(rconn));
458         goto cleanup;
459     }
460     frreq = rs_packet_frpkt(req);
461
462     major = setInitiatorIdentity(minor, ctx, &frreq->vps);
463     if (GSS_ERROR(major))
464         goto cleanup;
465
466     major = setAcceptorIdentity(minor, ctx, &frreq->vps);
467     if (GSS_ERROR(major))
468         goto cleanup;
469
470     major = gssEapRadiusAddAvp(minor, &frreq->vps,
471                                PW_EAP_MESSAGE, 0, inputToken);
472     if (GSS_ERROR(major))
473         goto cleanup;
474
475     if (ctx->acceptorCtx.state.length != 0) {
476         major = gssEapRadiusAddAvp(minor, &frreq->vps, PW_STATE, 0,
477                                    &ctx->acceptorCtx.state);
478         if (GSS_ERROR(major))
479             goto cleanup;
480
481         gss_release_buffer(&tmpMinor, &ctx->acceptorCtx.state);
482     }
483
484     if (rs_request_create(rconn, &request) != 0) {
485         major = gssEapRadiusMapError(minor, rs_err_conn_pop(rconn));
486         goto cleanup;
487     }
488
489     rs_request_add_reqpkt(request, req);
490     req = NULL;
491
492     if (rs_request_send(request, &resp) != 0) {
493         major = gssEapRadiusMapError(minor, rs_err_conn_pop(rconn));
494         goto cleanup;
495     }
496
497     assert(resp != NULL);
498
499     frresp = rs_packet_frpkt(resp);
500     switch (frresp->code) {
501     case PW_AUTHENTICATION_ACK:
502     case PW_ACCESS_CHALLENGE:
503         break;
504     case PW_AUTHENTICATION_REJECT:
505         *minor = GSSEAP_RADIUS_AUTH_FAILURE;
506         major = GSS_S_DEFECTIVE_CREDENTIAL;
507         goto cleanup;
508         break;
509     default:
510         *minor = GSSEAP_UNKNOWN_RADIUS_CODE;
511         major = GSS_S_FAILURE;
512         goto cleanup;
513         break;
514     }
515
516     major = gssEapRadiusGetAvp(minor, frresp->vps, PW_EAP_MESSAGE, 0,
517                                outputToken, TRUE);
518     if (major == GSS_S_UNAVAILABLE && frresp->code == PW_ACCESS_CHALLENGE) {
519         *minor = GSSEAP_MISSING_EAP_REQUEST;
520         major = GSS_S_DEFECTIVE_TOKEN;
521         goto cleanup;
522     } else if (GSS_ERROR(major))
523         goto cleanup;
524
525     if (frresp->code == PW_ACCESS_CHALLENGE) {
526         major = gssEapRadiusGetAvp(minor, frresp->vps, PW_STATE, 0,
527                                    &ctx->acceptorCtx.state, TRUE);
528         if (GSS_ERROR(major) && *minor != GSSEAP_NO_SUCH_ATTR)
529             goto cleanup;
530     } else {
531         ctx->acceptorCtx.vps = frresp->vps;
532         frresp->vps = NULL;
533
534         rs_conn_destroy(ctx->acceptorCtx.radConn);
535         ctx->acceptorCtx.radConn = NULL;
536
537         major = acceptReadyEap(minor, ctx, cred);
538         if (GSS_ERROR(major))
539             goto cleanup;
540
541         *smFlags |= SM_FLAG_TRANSITION;
542     }
543
544     major = GSS_S_CONTINUE_NEEDED;
545     *minor = 0;
546
547 cleanup:
548     if (request != NULL)
549         rs_request_destroy(request);
550     if (req != NULL)
551         rs_packet_destroy(req);
552
553     return major;
554 }
555
556 static OM_uint32
557 eapGssSmAcceptGssChannelBindings(OM_uint32 *minor,
558                                  gss_cred_id_t cred,
559                                  gss_ctx_id_t ctx,
560                                  gss_name_t target __attribute__((__unused__)),
561                                  gss_OID mech __attribute__((__unused__)),
562                                  OM_uint32 reqFlags __attribute__((__unused__)),
563                                  OM_uint32 timeReq __attribute__((__unused__)),
564                                  gss_channel_bindings_t chanBindings,
565                                  gss_buffer_t inputToken,
566                                  gss_buffer_t outputToken,
567                                  OM_uint32 *smFlags)
568 {
569     OM_uint32 major, tmpMinor;
570     gss_iov_buffer_desc iov[2];
571
572     iov[0].type = GSS_IOV_BUFFER_TYPE_DATA | GSS_IOV_BUFFER_FLAG_ALLOCATE;
573     iov[0].buffer.length = 0;
574     iov[0].buffer.value = NULL;
575
576     iov[1].type = GSS_IOV_BUFFER_TYPE_STREAM;
577     iov[1].buffer = *inputToken;
578
579     major = gssEapUnwrapOrVerifyMIC(minor, ctx, NULL, NULL,
580                                     iov, 2, TOK_TYPE_WRAP);
581     if (GSS_ERROR(major))
582         return GSS_S_BAD_BINDINGS;
583
584     if (chanBindings != GSS_C_NO_CHANNEL_BINDINGS &&
585         !bufferEqual(&iov[0].buffer, &chanBindings->application_data)) {
586         major = GSS_S_BAD_BINDINGS;
587         *minor = GSSEAP_BINDINGS_MISMATCH;
588     } else {
589         major = GSS_S_CONTINUE_NEEDED;
590         *minor = 0;
591     }
592
593     gss_release_buffer(&tmpMinor, &iov[0].buffer);
594
595     return major;
596 }
597
598 #ifdef GSSEAP_ENABLE_REAUTH
599 static OM_uint32
600 eapGssSmAcceptReauthCreds(OM_uint32 *minor,
601                           gss_cred_id_t cred,
602                           gss_ctx_id_t ctx,
603                           gss_name_t target __attribute__((__unused__)),
604                           gss_OID mech __attribute__((__unused__)),
605                           OM_uint32 reqFlags __attribute__((__unused__)),
606                           OM_uint32 timeReq __attribute__((__unused__)),
607                           gss_channel_bindings_t chanBindings __attribute__((__unused__)),
608                           gss_buffer_t inputToken,
609                           gss_buffer_t outputToken,
610                           OM_uint32 *smFlags)
611 {
612     OM_uint32 major;
613
614     /*
615      * If we're built with fast reauthentication enabled, then
616      * fabricate a ticket from the initiator to ourselves.
617      */
618     major = gssEapMakeReauthCreds(minor, ctx, cred, outputToken);
619     if (GSS_ERROR(major))
620         return major;
621
622     return major;
623 }
624 #endif
625
626 static OM_uint32
627 eapGssSmAcceptCompleteExts(OM_uint32 *minor,
628                            gss_cred_id_t cred,
629                            gss_ctx_id_t ctx,
630                            gss_name_t target,
631                            gss_OID mech,
632                            OM_uint32 reqFlags,
633                            OM_uint32 timeReq,
634                            gss_channel_bindings_t chanBindings,
635                            gss_buffer_t inputToken,
636                            gss_buffer_t outputToken,
637                            OM_uint32 *smFlags)
638 {
639     *minor = 0;
640     *smFlags |= SM_FLAG_TRANSITION | SM_FLAG_STOP_EVAL;
641     return (ctx->state == GSSEAP_STATE_INITIATOR_EXTS) ?
642         GSS_S_CONTINUE_NEEDED : GSS_S_COMPLETE;
643 }
644
645 static struct gss_eap_sm eapGssAcceptorSm[] = {
646 #ifdef GSSEAP_ENABLE_REAUTH
647     {
648         ITOK_TYPE_REAUTH_REQ,
649         ITOK_TYPE_REAUTH_RESP,
650         GSSEAP_STATE_INITIAL,
651         0,
652         eapGssSmAcceptGssReauth,
653     },
654 #endif
655     {
656         ITOK_TYPE_NONE,
657         ITOK_TYPE_EAP_REQ,
658         GSSEAP_STATE_INITIAL,
659         SM_ITOK_FLAG_CRITICAL | SM_ITOK_FLAG_REQUIRED,
660         eapGssSmAcceptIdentity,
661     },
662     {
663         ITOK_TYPE_EAP_RESP,
664         ITOK_TYPE_EAP_REQ,
665         GSSEAP_STATE_AUTHENTICATE,
666         SM_ITOK_FLAG_CRITICAL | SM_ITOK_FLAG_REQUIRED,
667         eapGssSmAcceptAuthenticate
668     },
669     {
670         ITOK_TYPE_GSS_CHANNEL_BINDINGS,
671         ITOK_TYPE_NONE,
672         GSSEAP_STATE_INITIATOR_EXTS,
673         SM_ITOK_FLAG_CRITICAL | SM_ITOK_FLAG_REQUIRED,
674         eapGssSmAcceptGssChannelBindings,
675     },
676     {
677         ITOK_TYPE_NONE,
678         ITOK_TYPE_NONE,
679         GSSEAP_STATE_INITIATOR_EXTS,
680         0,
681         eapGssSmAcceptCompleteExts,
682     },
683 #ifdef GSSEAP_ENABLE_REAUTH
684     {
685         ITOK_TYPE_NONE,
686         ITOK_TYPE_REAUTH_CREDS,
687         GSSEAP_STATE_ACCEPTOR_EXTS,
688         0,
689         eapGssSmAcceptReauthCreds,
690     },
691 #endif
692     {
693         ITOK_TYPE_NONE,
694         ITOK_TYPE_NONE,
695         GSSEAP_STATE_ACCEPTOR_EXTS,
696         0,
697         eapGssSmAcceptCompleteExts
698     },
699 };
700
701 OM_uint32
702 gss_accept_sec_context(OM_uint32 *minor,
703                        gss_ctx_id_t *context_handle,
704                        gss_cred_id_t cred,
705                        gss_buffer_t input_token,
706                        gss_channel_bindings_t input_chan_bindings,
707                        gss_name_t *src_name,
708                        gss_OID *mech_type,
709                        gss_buffer_t output_token,
710                        OM_uint32 *ret_flags,
711                        OM_uint32 *time_rec,
712                        gss_cred_id_t *delegated_cred_handle)
713 {
714     OM_uint32 major, tmpMinor;
715     gss_ctx_id_t ctx = *context_handle;
716
717     *minor = 0;
718
719     output_token->length = 0;
720     output_token->value = NULL;
721
722     if (src_name != NULL)
723         *src_name = GSS_C_NO_NAME;
724
725     if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
726         *minor = GSSEAP_TOK_TRUNC;
727         return GSS_S_DEFECTIVE_TOKEN;
728     }
729
730     if (ctx == GSS_C_NO_CONTEXT) {
731         major = gssEapAllocContext(minor, &ctx);
732         if (GSS_ERROR(major))
733             return major;
734
735         *context_handle = ctx;
736     }
737
738     GSSEAP_MUTEX_LOCK(&ctx->mutex);
739
740     if (cred == GSS_C_NO_CREDENTIAL) {
741         if (ctx->defaultCred == GSS_C_NO_CREDENTIAL) {
742             major = gssEapAcquireCred(minor,
743                                       GSS_C_NO_NAME,
744                                       GSS_C_NO_BUFFER,
745                                       GSS_C_INDEFINITE,
746                                       GSS_C_NO_OID_SET,
747                                       GSS_C_ACCEPT,
748                                       &ctx->defaultCred,
749                                       NULL,
750                                       NULL);
751             if (GSS_ERROR(major))
752                 goto cleanup;
753         }
754
755         cred = ctx->defaultCred;
756     }
757
758     GSSEAP_MUTEX_LOCK(&cred->mutex);
759
760     major = gssEapSmStep(minor,
761                          cred,
762                          ctx,
763                          GSS_C_NO_NAME,
764                          GSS_C_NO_OID,
765                          0,
766                          GSS_C_INDEFINITE,
767                          input_chan_bindings,
768                          input_token,
769                          output_token,
770                          eapGssAcceptorSm,
771                          sizeof(eapGssAcceptorSm) / sizeof(eapGssAcceptorSm[0]));
772     if (GSS_ERROR(major))
773         goto cleanup;
774
775     if (mech_type != NULL) {
776         if (!gssEapInternalizeOid(ctx->mechanismUsed, mech_type))
777             duplicateOid(&tmpMinor, ctx->mechanismUsed, mech_type);
778     }
779     if (ret_flags != NULL)
780         *ret_flags = ctx->gssFlags;
781     if (delegated_cred_handle != NULL)
782         *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
783
784     if (major == GSS_S_COMPLETE) {
785         if (src_name != NULL && ctx->initiatorName != GSS_C_NO_NAME) {
786             major = gssEapDuplicateName(&tmpMinor, ctx->initiatorName, src_name);
787             if (GSS_ERROR(major))
788                 goto cleanup;
789         }
790         if (time_rec != NULL) {
791             major = gssEapContextTime(&tmpMinor, ctx, time_rec);
792             if (GSS_ERROR(major))
793                 goto cleanup;
794         }
795     }
796
797     assert(ctx->state == GSSEAP_STATE_ESTABLISHED || major == GSS_S_CONTINUE_NEEDED);
798
799 cleanup:
800     if (cred != GSS_C_NO_CREDENTIAL)
801         GSSEAP_MUTEX_UNLOCK(&cred->mutex);
802     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
803
804     if (GSS_ERROR(major))
805         gssEapReleaseContext(&tmpMinor, context_handle);
806
807     return major;
808 }
809
810 #ifdef GSSEAP_ENABLE_REAUTH
811 static OM_uint32
812 acceptReadyKrb(OM_uint32 *minor,
813                gss_ctx_id_t ctx,
814                gss_cred_id_t cred,
815                const gss_name_t initiator,
816                const gss_OID mech,
817                OM_uint32 timeRec)
818 {
819     OM_uint32 major;
820
821     major = gssEapGlueToMechName(minor, ctx, initiator, &ctx->initiatorName);
822     if (GSS_ERROR(major))
823         return major;
824
825     if (cred->name != GSS_C_NO_NAME) {
826         major = gssEapDuplicateName(minor, cred->name, &ctx->acceptorName);
827         if (GSS_ERROR(major))
828             return major;
829     }
830
831     major = gssEapReauthComplete(minor, ctx, cred, mech, timeRec);
832     if (GSS_ERROR(major))
833         return major;
834
835     *minor = 0;
836     return GSS_S_COMPLETE;
837 }
838
839 static OM_uint32
840 eapGssSmAcceptGssReauth(OM_uint32 *minor,
841                         gss_cred_id_t cred,
842                         gss_ctx_id_t ctx,
843                         gss_name_t target __attribute__((__unused__)),
844                         gss_OID mech,
845                         OM_uint32 reqFlags __attribute__((__unused__)),
846                         OM_uint32 timeReq __attribute__((__unused__)),
847                         gss_channel_bindings_t chanBindings,
848                         gss_buffer_t inputToken,
849                         gss_buffer_t outputToken,
850                         OM_uint32 *smFlags)
851 {
852     OM_uint32 major, tmpMinor;
853     gss_name_t krbInitiator = GSS_C_NO_NAME;
854     OM_uint32 gssFlags, timeRec = GSS_C_INDEFINITE;
855
856     /*
857      * If we're built with fast reauthentication support, it's valid
858      * for an initiator to send a GSS reauthentication token as its
859      * initial context token, causing us to short-circuit the state
860      * machine and process Kerberos GSS messages instead.
861      */
862
863     ctx->flags |= CTX_FLAG_KRB_REAUTH;
864
865     major = gssAcceptSecContext(minor,
866                                 &ctx->kerberosCtx,
867                                 cred->krbCred,
868                                 inputToken,
869                                 chanBindings,
870                                 &krbInitiator,
871                                 &mech,
872                                 outputToken,
873                                 &gssFlags,
874                                 &timeRec,
875                                 NULL);
876     if (major == GSS_S_COMPLETE) {
877         major = acceptReadyKrb(minor, ctx, cred,
878                                krbInitiator, mech, timeRec);
879         if (major == GSS_S_COMPLETE) {
880             ctx->state = GSSEAP_STATE_ESTABLISHED;
881             *smFlags |= SM_FLAG_STOP_EVAL;
882         }
883     }
884
885     ctx->gssFlags = gssFlags;
886
887     gssReleaseName(&tmpMinor, &krbInitiator);
888
889     return major;
890 }
891 #endif /* GSSEAP_ENABLE_REAUTH */