make state transition explicit rather than side-effect of GSS status 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                         int *transitionState);
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                        int *transitionState)
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     *transitionState = 1;
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                            int *transitionState)
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         *transitionState = 1;
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                                  int *transitionState)
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     }
589
590     gss_release_buffer(&tmpMinor, &iov[0].buffer);
591
592     return major;
593 }
594
595 #ifdef GSSEAP_ENABLE_REAUTH
596 static OM_uint32
597 eapGssSmAcceptReauthCreds(OM_uint32 *minor,
598                           gss_cred_id_t cred,
599                           gss_ctx_id_t ctx,
600                           gss_name_t target __attribute__((__unused__)),
601                           gss_OID mech __attribute__((__unused__)),
602                           OM_uint32 reqFlags __attribute__((__unused__)),
603                           OM_uint32 timeReq __attribute__((__unused__)),
604                           gss_channel_bindings_t chanBindings __attribute__((__unused__)),
605                           gss_buffer_t inputToken,
606                           gss_buffer_t outputToken,
607                           int *transitionState)
608 {
609     OM_uint32 major;
610
611     /*
612      * If we're built with fast reauthentication enabled, then
613      * fabricate a ticket from the initiator to ourselves.
614      */
615     major = gssEapMakeReauthCreds(minor, ctx, cred, outputToken);
616     if (GSS_ERROR(major))
617         return major;
618
619     return major;
620 }
621 #endif
622
623 static OM_uint32
624 eapGssSmAcceptNegoExtFinished(OM_uint32 *minor,
625                               gss_cred_id_t cred,
626                               gss_ctx_id_t ctx,
627                               gss_name_t target __attribute__((__unused__)),
628                               gss_OID mech __attribute__((__unused__)),
629                               OM_uint32 reqFlags __attribute__((__unused__)),
630                               OM_uint32 timeReq __attribute__((__unused__)),
631                               gss_channel_bindings_t chanBindings __attribute__((__unused__)),
632                               gss_buffer_t inputToken,
633                               gss_buffer_t outputToken,
634                               int *transitionState)
635 {
636     *minor = 0;
637     *transitionState = 1;
638     return GSS_S_COMPLETE;
639 }
640
641 static struct gss_eap_sm eapGssAcceptorSm[] = {
642 #ifdef GSSEAP_ENABLE_REAUTH
643     {
644         ITOK_TYPE_REAUTH_REQ,
645         ITOK_TYPE_REAUTH_RESP,
646         GSSEAP_STATE_INITIAL,
647         0, /* critical */
648         0, /* required */
649         eapGssSmAcceptGssReauth,
650     },
651 #endif
652     {
653         ITOK_TYPE_NONE,
654         ITOK_TYPE_EAP_REQ,
655         GSSEAP_STATE_INITIAL,
656         1, /* critical */
657         1, /* required */
658         eapGssSmAcceptIdentity,
659     },
660     {
661         ITOK_TYPE_EAP_RESP,
662         ITOK_TYPE_EAP_REQ,
663         GSSEAP_STATE_AUTHENTICATE,
664         1, /* critical */
665         1, /* required */
666         eapGssSmAcceptAuthenticate
667     },
668     {
669         ITOK_TYPE_GSS_CHANNEL_BINDINGS,
670         ITOK_TYPE_NONE,
671         GSSEAP_STATE_NEGO_EXT,
672         1, /* critical */
673         1, /* required */
674         eapGssSmAcceptGssChannelBindings,
675     },
676 #ifdef GSSEAP_ENABLE_REAUTH
677     {
678         ITOK_TYPE_NONE,
679         ITOK_TYPE_REAUTH_CREDS,
680         GSSEAP_STATE_NEGO_EXT,
681         0, /* critical */
682         0, /* required */
683         eapGssSmAcceptReauthCreds,
684     },
685 #endif
686     {
687         ITOK_TYPE_NONE,
688         ITOK_TYPE_NONE,
689         GSSEAP_STATE_NEGO_EXT,
690         1, /* critical */
691         1, /* required */
692         eapGssSmAcceptNegoExtFinished
693     },
694 };
695
696 OM_uint32
697 gss_accept_sec_context(OM_uint32 *minor,
698                        gss_ctx_id_t *context_handle,
699                        gss_cred_id_t cred,
700                        gss_buffer_t input_token,
701                        gss_channel_bindings_t input_chan_bindings,
702                        gss_name_t *src_name,
703                        gss_OID *mech_type,
704                        gss_buffer_t output_token,
705                        OM_uint32 *ret_flags,
706                        OM_uint32 *time_rec,
707                        gss_cred_id_t *delegated_cred_handle)
708 {
709     OM_uint32 major, tmpMinor;
710     gss_ctx_id_t ctx = *context_handle;
711
712     *minor = 0;
713
714     output_token->length = 0;
715     output_token->value = NULL;
716
717     if (src_name != NULL)
718         *src_name = GSS_C_NO_NAME;
719
720     if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
721         *minor = GSSEAP_TOK_TRUNC;
722         return GSS_S_DEFECTIVE_TOKEN;
723     }
724
725     if (ctx == GSS_C_NO_CONTEXT) {
726         major = gssEapAllocContext(minor, &ctx);
727         if (GSS_ERROR(major))
728             return major;
729
730         *context_handle = ctx;
731     }
732
733     GSSEAP_MUTEX_LOCK(&ctx->mutex);
734
735     if (cred == GSS_C_NO_CREDENTIAL) {
736         if (ctx->defaultCred == GSS_C_NO_CREDENTIAL) {
737             major = gssEapAcquireCred(minor,
738                                       GSS_C_NO_NAME,
739                                       GSS_C_NO_BUFFER,
740                                       GSS_C_INDEFINITE,
741                                       GSS_C_NO_OID_SET,
742                                       GSS_C_ACCEPT,
743                                       &ctx->defaultCred,
744                                       NULL,
745                                       NULL);
746             if (GSS_ERROR(major))
747                 goto cleanup;
748         }
749
750         cred = ctx->defaultCred;
751     }
752
753     GSSEAP_MUTEX_LOCK(&cred->mutex);
754
755     major = gssEapSmStep(minor,
756                          cred,
757                          ctx,
758                          GSS_C_NO_NAME,
759                          GSS_C_NO_OID,
760                          0,
761                          GSS_C_INDEFINITE,
762                          input_chan_bindings,
763                          input_token,
764                          output_token,
765                          eapGssAcceptorSm,
766                          sizeof(eapGssAcceptorSm) / sizeof(eapGssAcceptorSm[0]));
767     if (GSS_ERROR(major))
768         goto cleanup;
769
770     if (mech_type != NULL) {
771         if (!gssEapInternalizeOid(ctx->mechanismUsed, mech_type))
772             duplicateOid(&tmpMinor, ctx->mechanismUsed, mech_type);
773     }
774     if (ret_flags != NULL)
775         *ret_flags = ctx->gssFlags;
776     if (delegated_cred_handle != NULL)
777         *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
778
779     if (major == GSS_S_COMPLETE) {
780         if (src_name != NULL && ctx->initiatorName != GSS_C_NO_NAME) {
781             major = gssEapDuplicateName(&tmpMinor, ctx->initiatorName, src_name);
782             if (GSS_ERROR(major))
783                 goto cleanup;
784         }
785         if (time_rec != NULL) {
786             major = gssEapContextTime(&tmpMinor, ctx, time_rec);
787             if (GSS_ERROR(major))
788                 goto cleanup;
789         }
790     }
791
792     assert(ctx->state == GSSEAP_STATE_ESTABLISHED || major == GSS_S_CONTINUE_NEEDED);
793
794 cleanup:
795     if (cred != GSS_C_NO_CREDENTIAL)
796         GSSEAP_MUTEX_UNLOCK(&cred->mutex);
797     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
798
799     if (GSS_ERROR(major))
800         gssEapReleaseContext(&tmpMinor, context_handle);
801
802     return major;
803 }
804
805 #ifdef GSSEAP_ENABLE_REAUTH
806 static OM_uint32
807 acceptReadyKrb(OM_uint32 *minor,
808                gss_ctx_id_t ctx,
809                gss_cred_id_t cred,
810                const gss_name_t initiator,
811                const gss_OID mech,
812                OM_uint32 timeRec)
813 {
814     OM_uint32 major;
815
816     major = gssEapGlueToMechName(minor, ctx, initiator, &ctx->initiatorName);
817     if (GSS_ERROR(major))
818         return major;
819
820     if (cred->name != GSS_C_NO_NAME) {
821         major = gssEapDuplicateName(minor, cred->name, &ctx->acceptorName);
822         if (GSS_ERROR(major))
823             return major;
824     }
825
826     major = gssEapReauthComplete(minor, ctx, cred, mech, timeRec);
827     if (GSS_ERROR(major))
828         return major;
829
830     ctx->state = GSSEAP_STATE_NEGO_EXT; /* skip */
831
832     *minor = 0;
833     return GSS_S_COMPLETE; /* advance state */
834 }
835
836 static OM_uint32
837 eapGssSmAcceptGssReauth(OM_uint32 *minor,
838                         gss_cred_id_t cred,
839                         gss_ctx_id_t ctx,
840                         gss_name_t target __attribute__((__unused__)),
841                         gss_OID mech,
842                         OM_uint32 reqFlags __attribute__((__unused__)),
843                         OM_uint32 timeReq __attribute__((__unused__)),
844                         gss_channel_bindings_t chanBindings,
845                         gss_buffer_t inputToken,
846                         gss_buffer_t outputToken,
847                         int *transitionState)
848 {
849     OM_uint32 major, tmpMinor;
850     gss_name_t krbInitiator = GSS_C_NO_NAME;
851     OM_uint32 gssFlags, timeRec = GSS_C_INDEFINITE;
852
853     /*
854      * If we're built with fast reauthentication support, it's valid
855      * for an initiator to send a GSS reauthentication token as its
856      * initial context token, causing us to short-circuit the state
857      * machine and process Kerberos GSS messages instead.
858      */
859
860     ctx->flags |= CTX_FLAG_KRB_REAUTH;
861
862     major = gssAcceptSecContext(minor,
863                                 &ctx->kerberosCtx,
864                                 cred->krbCred,
865                                 inputToken,
866                                 chanBindings,
867                                 &krbInitiator,
868                                 &mech,
869                                 outputToken,
870                                 &gssFlags,
871                                 &timeRec,
872                                 NULL);
873     if (major == GSS_S_COMPLETE) {
874         major = acceptReadyKrb(minor, ctx, cred,
875                                krbInitiator, mech, timeRec);
876         *transitionState = 1;
877     }
878
879     ctx->gssFlags = gssFlags;
880
881     gssReleaseName(&tmpMinor, &krbInitiator);
882
883     return major;
884 }
885 #endif /* GSSEAP_ENABLE_REAUTH */