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