Merge branch 'master' into tlv-mic
[moonshot.git] / mech_eap / 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,
46                         gss_OID mech,
47                         OM_uint32 reqFlags,
48                         OM_uint32 timeReq,
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->mechanismUsed,
86                              &ctx->initiatorName);
87     if (GSS_ERROR(major))
88         return major;
89
90     major = gssEapRadiusGetRawAvp(minor, ctx->acceptorCtx.vps,
91                                   PW_MS_MPPE_SEND_KEY, VENDORPEC_MS, &vp);
92     if (GSS_ERROR(major)) {
93         *minor = GSSEAP_KEY_UNAVAILABLE;
94         return GSS_S_UNAVAILABLE;
95     }
96
97     major = gssEapDeriveRfc3961Key(minor,
98                                    vp->vp_octets,
99                                    vp->length,
100                                    ctx->encryptionType,
101                                    &ctx->rfc3961Key);
102     if (GSS_ERROR(major))
103         return major;
104
105     major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
106                                        &ctx->checksumType);
107     if (GSS_ERROR(major))
108         return major;
109
110     major = sequenceInit(minor,
111                          &ctx->seqState, ctx->recvSeq,
112                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
113                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
114                          TRUE);
115     if (GSS_ERROR(major))
116         return major;
117
118     major = gssEapCreateAttrContext(minor, cred, ctx,
119                                     &ctx->initiatorName->attrCtx,
120                                     &ctx->expiryTime);
121     if (GSS_ERROR(major))
122         return major;
123
124     *minor = 0;
125     return GSS_S_COMPLETE;
126 }
127
128 static OM_uint32
129 gssEapSupportedInitiatorExts[] = {
130 };
131
132 static struct gss_eap_itok_map
133 gssEapAcceptorExtsFlagMap[] = {
134     { ITOK_TYPE_REAUTH_CREDS, CTX_FLAG_KRB_REAUTH_SUPPORTED },
135 };
136
137 static OM_uint32
138 eapGssSmAcceptExts(OM_uint32 *minor,
139                    gss_cred_id_t cred GSSEAP_UNUSED,
140                    gss_ctx_id_t ctx GSSEAP_UNUSED,
141                    gss_name_t target GSSEAP_UNUSED,
142                    gss_OID mech GSSEAP_UNUSED,
143                    OM_uint32 reqFlags GSSEAP_UNUSED,
144                    OM_uint32 timeReq GSSEAP_UNUSED,
145                    gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
146                    gss_buffer_t inputToken,
147                    gss_buffer_t outputToken,
148                    OM_uint32 *smFlags GSSEAP_UNUSED)
149 {
150     OM_uint32 major;
151
152     major = gssEapProcessSupportedExts(minor, inputToken,
153                                        gssEapAcceptorExtsFlagMap,
154                                         sizeof(gssEapAcceptorExtsFlagMap) /
155                                        sizeof(gssEapAcceptorExtsFlagMap[0]),
156                                        &ctx->flags);
157     if (GSS_ERROR(major))
158         return major;
159
160     major = gssEapEncodeSupportedExts(minor,
161                                       gssEapSupportedInitiatorExts,
162                                       sizeof(gssEapSupportedInitiatorExts) /
163                                         sizeof(gssEapSupportedInitiatorExts[0]),
164                                       outputToken);
165     if (GSS_ERROR(major))
166         return major;
167
168     return GSS_S_CONTINUE_NEEDED;
169 }
170
171 static OM_uint32
172 eapGssSmAcceptAcceptorName(OM_uint32 *minor,
173                            gss_cred_id_t cred GSSEAP_UNUSED,
174                            gss_ctx_id_t ctx,
175                            gss_name_t target GSSEAP_UNUSED,
176                            gss_OID mech GSSEAP_UNUSED,
177                            OM_uint32 reqFlags GSSEAP_UNUSED,
178                            OM_uint32 timeReq GSSEAP_UNUSED,
179                            gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
180                            gss_buffer_t inputToken GSSEAP_UNUSED,
181                            gss_buffer_t outputToken,
182                            OM_uint32 *smFlags GSSEAP_UNUSED)
183 {
184     OM_uint32 major;
185
186     /* XXX TODO import and validate name from inputToken */
187
188     if (ctx->acceptorName != GSS_C_NO_NAME) {
189         /* Send desired target name to acceptor */
190         major = gssEapDisplayName(minor, ctx->acceptorName,
191                                   outputToken, NULL);
192         if (GSS_ERROR(major))
193             return major;
194     }
195
196     return GSS_S_CONTINUE_NEEDED;
197 }
198
199 #ifdef GSSEAP_DEBUG
200 static OM_uint32
201 eapGssSmAcceptVendorInfo(OM_uint32 *minor,
202                          gss_cred_id_t cred GSSEAP_UNUSED,
203                          gss_ctx_id_t ctx GSSEAP_UNUSED,
204                          gss_name_t target GSSEAP_UNUSED,
205                          gss_OID mech GSSEAP_UNUSED,
206                          OM_uint32 reqFlags GSSEAP_UNUSED,
207                          OM_uint32 timeReq GSSEAP_UNUSED,
208                          gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
209                          gss_buffer_t inputToken,
210                          gss_buffer_t outputToken GSSEAP_UNUSED,
211                          OM_uint32 *smFlags GSSEAP_UNUSED)
212 {
213     fprintf(stderr, "GSS-EAP: vendor: %.*s\n",
214             (int)inputToken->length, (char *)inputToken->value);
215
216     *minor = 0;
217     return GSS_S_CONTINUE_NEEDED;
218 }
219 #endif
220
221
222 /*
223  * Emit a identity EAP request to force the initiator (peer) to identify
224  * itself.
225  */
226 static OM_uint32
227 eapGssSmAcceptIdentity(OM_uint32 *minor,
228                        gss_cred_id_t cred,
229                        gss_ctx_id_t ctx,
230                        gss_name_t target GSSEAP_UNUSED,
231                        gss_OID mech GSSEAP_UNUSED,
232                        OM_uint32 reqFlags GSSEAP_UNUSED,
233                        OM_uint32 timeReq GSSEAP_UNUSED,
234                        gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
235                        gss_buffer_t inputToken,
236                        gss_buffer_t outputToken,
237                        OM_uint32 *smFlags)
238 {
239     OM_uint32 major;
240     struct wpabuf *reqData;
241     gss_buffer_desc pktBuffer;
242
243     if (!gssEapCredAvailable(cred, ctx->mechanismUsed)) {
244         *minor = GSSEAP_CRED_MECH_MISMATCH;
245         return GSS_S_BAD_MECH;
246     }
247
248     if (inputToken != GSS_C_NO_BUFFER && inputToken->length != 0) {
249         *minor = GSSEAP_WRONG_SIZE;
250         return GSS_S_DEFECTIVE_TOKEN;
251     }
252
253     reqData = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_IDENTITY, 0,
254                             EAP_CODE_REQUEST, 0);
255     if (reqData == NULL) {
256         *minor = ENOMEM;
257         return GSS_S_FAILURE;
258     }
259
260     pktBuffer.length = wpabuf_len(reqData);
261     pktBuffer.value = (void *)wpabuf_head(reqData);
262
263     major = duplicateBuffer(minor, &pktBuffer, outputToken);
264     if (GSS_ERROR(major))
265         return major;
266
267     wpabuf_free(reqData);
268
269     GSSEAP_SM_TRANSITION_NEXT(ctx);
270
271     *minor = 0;
272     *smFlags |= SM_FLAG_SEND_TOKEN | SM_FLAG_OUTPUT_TOKEN_CRITICAL;
273
274     return GSS_S_CONTINUE_NEEDED;
275 }
276
277 /*
278  * Returns TRUE if the input token contains an EAP identity response.
279  */
280 static int
281 isIdentityResponseP(gss_buffer_t inputToken)
282 {
283     struct wpabuf respData;
284
285     wpabuf_set(&respData, inputToken->value, inputToken->length);
286
287     return (eap_get_type(&respData) == EAP_TYPE_IDENTITY);
288 }
289
290 /*
291  * Save the asserted initiator identity from the EAP identity response.
292  */
293 static OM_uint32
294 importInitiatorIdentity(OM_uint32 *minor,
295                         gss_ctx_id_t ctx,
296                         gss_buffer_t inputToken)
297 {
298     OM_uint32 tmpMinor;
299     struct wpabuf respData;
300     const unsigned char *pos;
301     size_t len;
302     gss_buffer_desc nameBuf;
303
304     wpabuf_set(&respData, inputToken->value, inputToken->length);
305
306     pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_IDENTITY,
307                            &respData, &len);
308     if (pos == NULL) {
309         *minor = GSSEAP_PEER_BAD_MESSAGE;
310         return GSS_S_DEFECTIVE_TOKEN;
311     }
312
313     nameBuf.value = (void *)pos;
314     nameBuf.length = len;
315
316     gssEapReleaseName(&tmpMinor, &ctx->initiatorName);
317
318     return gssEapImportName(minor, &nameBuf, GSS_C_NT_USER_NAME,
319                             ctx->mechanismUsed, &ctx->initiatorName);
320 }
321
322 /*
323  * Pass the asserted initiator identity to the authentication server.
324  */
325 static OM_uint32
326 setInitiatorIdentity(OM_uint32 *minor,
327                      gss_ctx_id_t ctx,
328                      VALUE_PAIR **vps)
329 {
330     OM_uint32 major, tmpMinor;
331     gss_buffer_desc nameBuf;
332
333     /*
334      * We should have got an EAP identity response, but if we didn't, then
335      * we will just avoid sending User-Name. Note that radsecproxy requires
336      * User-Name to be sent on every request (presumably so it can remain
337      * stateless).
338      */
339     if (ctx->initiatorName != GSS_C_NO_NAME) {
340         major = gssEapDisplayName(minor, ctx->initiatorName, &nameBuf, NULL);
341         if (GSS_ERROR(major))
342             return major;
343
344         major = gssEapRadiusAddAvp(minor, vps, PW_USER_NAME, 0, &nameBuf);
345         if (GSS_ERROR(major))
346             return major;
347
348         gss_release_buffer(&tmpMinor, &nameBuf);
349     }
350
351     *minor = 0;
352     return GSS_S_COMPLETE;
353 }
354
355 /*
356  * Pass the asserted acceptor identity to the authentication server.
357  */
358 static OM_uint32
359 setAcceptorIdentity(OM_uint32 *minor,
360                     gss_ctx_id_t ctx,
361                     VALUE_PAIR **vps)
362 {
363     OM_uint32 major;
364     gss_buffer_desc nameBuf;
365     krb5_context krbContext = NULL;
366     krb5_principal krbPrinc;
367     struct rs_context *rc = ctx->acceptorCtx.radContext;
368
369     assert(rc != NULL);
370
371     if (ctx->acceptorName == GSS_C_NO_NAME) {
372         *minor = 0;
373         return GSS_S_COMPLETE;
374     }
375
376     if ((ctx->acceptorName->flags & NAME_FLAG_SERVICE) == 0) {
377         *minor = GSSEAP_BAD_SERVICE_NAME;
378         return GSS_S_BAD_NAME;
379     }
380
381     GSSEAP_KRB_INIT(&krbContext);
382
383     krbPrinc = ctx->acceptorName->krbPrincipal;
384     assert(krbPrinc != NULL);
385     assert(KRB_PRINC_LENGTH(krbPrinc) >= 2);
386
387     /* Acceptor-Service-Name */
388     krbPrincComponentToGssBuffer(krbPrinc, 0, &nameBuf);
389
390     major = gssEapRadiusAddAvp(minor, vps,
391                                PW_GSS_ACCEPTOR_SERVICE_NAME,
392                                VENDORPEC_UKERNA,
393                                &nameBuf);
394     if (GSS_ERROR(major))
395         return major;
396
397     /* Acceptor-Host-Name */
398     krbPrincComponentToGssBuffer(krbPrinc, 1, &nameBuf);
399
400     major = gssEapRadiusAddAvp(minor, vps,
401                                PW_GSS_ACCEPTOR_HOST_NAME,
402                                VENDORPEC_UKERNA,
403                                &nameBuf);
404     if (GSS_ERROR(major))
405         return major;
406
407     if (KRB_PRINC_LENGTH(krbPrinc) > 2) {
408         /* Acceptor-Service-Specific */
409         krb5_principal_data ssiPrinc = *krbPrinc;
410         char *ssi;
411
412         KRB_PRINC_LENGTH(&ssiPrinc) -= 2;
413         KRB_PRINC_NAME(&ssiPrinc) += 2;
414
415         *minor = krb5_unparse_name_flags(krbContext, &ssiPrinc,
416                                          KRB5_PRINCIPAL_UNPARSE_NO_REALM, &ssi);
417         if (*minor != 0)
418             return GSS_S_FAILURE;
419
420         nameBuf.value = ssi;
421         nameBuf.length = strlen(ssi);
422
423         major = gssEapRadiusAddAvp(minor, vps,
424                                    PW_GSS_ACCEPTOR_SERVICE_SPECIFIC,
425                                    VENDORPEC_UKERNA,
426                                    &nameBuf);
427
428         if (GSS_ERROR(major)) {
429             krb5_free_unparsed_name(krbContext, ssi);
430             return major;
431         }
432         krb5_free_unparsed_name(krbContext, ssi);
433     }
434
435     krbPrincRealmToGssBuffer(krbPrinc, &nameBuf);
436     if (nameBuf.length != 0) {
437         /* Acceptor-Realm-Name */
438         major = gssEapRadiusAddAvp(minor, vps,
439                                    PW_GSS_ACCEPTOR_REALM_NAME,
440                                    VENDORPEC_UKERNA,
441                                    &nameBuf);
442         if (GSS_ERROR(major))
443             return major;
444     }
445
446     *minor = 0;
447     return GSS_S_COMPLETE;
448 }
449
450 /*
451  * Allocate a RadSec handle
452  */
453 static OM_uint32
454 createRadiusHandle(OM_uint32 *minor,
455                    gss_cred_id_t cred,
456                    gss_ctx_id_t ctx)
457 {
458     struct gss_eap_acceptor_ctx *actx = &ctx->acceptorCtx;
459     const char *configFile = RS_CONFIG_FILE;
460     const char *configStanza = "gss-eap";
461     struct rs_alloc_scheme ralloc;
462     struct rs_error *err;
463
464     assert(actx->radContext == NULL);
465     assert(actx->radConn == NULL);
466
467     if (rs_context_create(&actx->radContext, RS_DICT_FILE) != 0) {
468         *minor = GSSEAP_RADSEC_CONTEXT_FAILURE;
469         return GSS_S_FAILURE;
470     }
471
472     if (cred->radiusConfigFile != NULL)
473         configFile = cred->radiusConfigFile;
474     if (cred->radiusConfigStanza != NULL)
475         configStanza = cred->radiusConfigStanza;
476
477     ralloc.calloc  = GSSEAP_CALLOC;
478     ralloc.malloc  = GSSEAP_MALLOC;
479     ralloc.free    = GSSEAP_FREE;
480     ralloc.realloc = GSSEAP_REALLOC;
481
482     rs_context_set_alloc_scheme(actx->radContext, &ralloc);
483
484     if (rs_context_read_config(actx->radContext, configFile) != 0) {
485         err = rs_err_ctx_pop(actx->radContext);
486         goto fail;
487     }
488
489     if (rs_conn_create(actx->radContext, &actx->radConn, configStanza) != 0) {
490         err = rs_err_conn_pop(actx->radConn);
491         goto fail;
492     }
493
494     if (actx->radServer != NULL) {
495         if (rs_conn_select_peer(actx->radConn, actx->radServer) != 0) {
496             err = rs_err_conn_pop(actx->radConn);
497             goto fail;
498         }
499     }
500
501     *minor = 0;
502     return GSS_S_COMPLETE;
503
504 fail:
505     return gssEapRadiusMapError(minor, err);
506 }
507
508 /*
509  * Process a EAP response from the initiator.
510  */
511 static OM_uint32
512 eapGssSmAcceptAuthenticate(OM_uint32 *minor,
513                            gss_cred_id_t cred,
514                            gss_ctx_id_t ctx,
515                            gss_name_t target GSSEAP_UNUSED,
516                            gss_OID mech GSSEAP_UNUSED,
517                            OM_uint32 reqFlags GSSEAP_UNUSED,
518                            OM_uint32 timeReq GSSEAP_UNUSED,
519                            gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
520                            gss_buffer_t inputToken,
521                            gss_buffer_t outputToken,
522                            OM_uint32 *smFlags)
523 {
524     OM_uint32 major, tmpMinor;
525     struct rs_connection *rconn;
526     struct rs_request *request = NULL;
527     struct rs_packet *req = NULL, *resp = NULL;
528     struct radius_packet *frreq, *frresp;
529
530     if (ctx->acceptorCtx.radContext == NULL) {
531         /* May be NULL from an imported partial context */
532         major = createRadiusHandle(minor, cred, ctx);
533         if (GSS_ERROR(major))
534             goto cleanup;
535     }
536
537     if (isIdentityResponseP(inputToken)) {
538         major = importInitiatorIdentity(minor, ctx, inputToken);
539         if (GSS_ERROR(major))
540             return major;
541     }
542
543     rconn = ctx->acceptorCtx.radConn;
544
545     if (rs_packet_create_authn_request(rconn, &req, NULL, NULL) != 0) {
546         major = gssEapRadiusMapError(minor, rs_err_conn_pop(rconn));
547         goto cleanup;
548     }
549     frreq = rs_packet_frpkt(req);
550
551     major = setInitiatorIdentity(minor, ctx, &frreq->vps);
552     if (GSS_ERROR(major))
553         goto cleanup;
554
555     major = setAcceptorIdentity(minor, ctx, &frreq->vps);
556     if (GSS_ERROR(major))
557         goto cleanup;
558
559     major = gssEapRadiusAddAvp(minor, &frreq->vps,
560                                PW_EAP_MESSAGE, 0, inputToken);
561     if (GSS_ERROR(major))
562         goto cleanup;
563
564     if (ctx->acceptorCtx.state.length != 0) {
565         major = gssEapRadiusAddAvp(minor, &frreq->vps, PW_STATE, 0,
566                                    &ctx->acceptorCtx.state);
567         if (GSS_ERROR(major))
568             goto cleanup;
569
570         gss_release_buffer(&tmpMinor, &ctx->acceptorCtx.state);
571     }
572
573     if (rs_request_create(rconn, &request) != 0) {
574         major = gssEapRadiusMapError(minor, rs_err_conn_pop(rconn));
575         goto cleanup;
576     }
577
578     rs_request_add_reqpkt(request, req);
579     req = NULL;
580
581     if (rs_request_send(request, &resp) != 0) {
582         major = gssEapRadiusMapError(minor, rs_err_conn_pop(rconn));
583         goto cleanup;
584     }
585
586     assert(resp != NULL);
587
588     frresp = rs_packet_frpkt(resp);
589     switch (frresp->code) {
590     case PW_ACCESS_CHALLENGE:
591     case PW_AUTHENTICATION_ACK:
592         break;
593     case PW_AUTHENTICATION_REJECT:
594         *minor = GSSEAP_RADIUS_AUTH_FAILURE;
595         major = GSS_S_DEFECTIVE_CREDENTIAL;
596         goto cleanup;
597         break;
598     default:
599         *minor = GSSEAP_UNKNOWN_RADIUS_CODE;
600         major = GSS_S_FAILURE;
601         goto cleanup;
602         break;
603     }
604
605     major = gssEapRadiusGetAvp(minor, frresp->vps, PW_EAP_MESSAGE, 0,
606                                outputToken, TRUE);
607     if (major == GSS_S_UNAVAILABLE && frresp->code == PW_ACCESS_CHALLENGE) {
608         *minor = GSSEAP_MISSING_EAP_REQUEST;
609         major = GSS_S_DEFECTIVE_TOKEN;
610         goto cleanup;
611     } else if (GSS_ERROR(major))
612         goto cleanup;
613
614     if (frresp->code == PW_ACCESS_CHALLENGE) {
615         major = gssEapRadiusGetAvp(minor, frresp->vps, PW_STATE, 0,
616                                    &ctx->acceptorCtx.state, TRUE);
617         if (GSS_ERROR(major) && *minor != GSSEAP_NO_SUCH_ATTR)
618             goto cleanup;
619     } else {
620         ctx->acceptorCtx.vps = frresp->vps;
621         frresp->vps = NULL;
622
623         major = acceptReadyEap(minor, ctx, cred);
624         if (GSS_ERROR(major))
625             goto cleanup;
626
627         GSSEAP_SM_TRANSITION_NEXT(ctx);
628     }
629
630     major = GSS_S_CONTINUE_NEEDED;
631     *minor = 0;
632     *smFlags |= SM_FLAG_SEND_TOKEN | SM_FLAG_OUTPUT_TOKEN_CRITICAL;
633
634 cleanup:
635     if (request != NULL)
636         rs_request_destroy(request);
637     if (req != NULL)
638         rs_packet_destroy(req);
639     if (resp != NULL)
640         rs_packet_destroy(resp);
641     if (GSSEAP_SM_STATE(ctx) == GSSEAP_STATE_INITIATOR_EXTS) {
642         assert(major == GSS_S_CONTINUE_NEEDED);
643
644         rs_conn_destroy(ctx->acceptorCtx.radConn);
645         ctx->acceptorCtx.radConn = NULL;
646     }
647
648     return major;
649 }
650
651 static OM_uint32
652 eapGssSmAcceptGssFlags(OM_uint32 *minor,
653                        gss_cred_id_t cred GSSEAP_UNUSED,
654                        gss_ctx_id_t ctx,
655                        gss_name_t target GSSEAP_UNUSED,
656                        gss_OID mech GSSEAP_UNUSED,
657                        OM_uint32 reqFlags GSSEAP_UNUSED,
658                        OM_uint32 timeReq GSSEAP_UNUSED,
659                        gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
660                        gss_buffer_t inputToken,
661                        gss_buffer_t outputToken GSSEAP_UNUSED,
662                        OM_uint32 *smFlags GSSEAP_UNUSED)
663 {
664     unsigned char *p;
665     OM_uint32 initiatorGssFlags;
666
667     assert((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0);
668
669     if (inputToken->length < 4) {
670         *minor = GSSEAP_TOK_TRUNC;
671         return GSS_S_DEFECTIVE_TOKEN;
672     }
673
674     /* allow flags to grow for future expansion */
675     p = (unsigned char *)inputToken->value + inputToken->length - 4;
676
677     initiatorGssFlags = load_uint32_be(p);
678     initiatorGssFlags &= GSSEAP_WIRE_FLAGS_MASK;
679
680     ctx->gssFlags |= initiatorGssFlags;
681
682     return GSS_S_CONTINUE_NEEDED;
683 }
684
685 static OM_uint32
686 eapGssSmAcceptGssChannelBindings(OM_uint32 *minor,
687                                  gss_cred_id_t cred GSSEAP_UNUSED,
688                                  gss_ctx_id_t ctx,
689                                  gss_name_t target GSSEAP_UNUSED,
690                                  gss_OID mech GSSEAP_UNUSED,
691                                  OM_uint32 reqFlags GSSEAP_UNUSED,
692                                  OM_uint32 timeReq GSSEAP_UNUSED,
693                                  gss_channel_bindings_t chanBindings,
694                                  gss_buffer_t inputToken,
695                                  gss_buffer_t outputToken GSSEAP_UNUSED,
696                                  OM_uint32 *smFlags GSSEAP_UNUSED)
697 {
698     OM_uint32 major, tmpMinor;
699     gss_iov_buffer_desc iov[2];
700
701     assert((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0);
702
703     iov[0].type = GSS_IOV_BUFFER_TYPE_DATA | GSS_IOV_BUFFER_FLAG_ALLOCATE;
704     iov[0].buffer.length = 0;
705     iov[0].buffer.value = NULL;
706
707     iov[1].type = GSS_IOV_BUFFER_TYPE_STREAM;
708     iov[1].buffer = *inputToken;
709
710     major = gssEapUnwrapOrVerifyMIC(minor, ctx, NULL, NULL,
711                                     iov, 2, TOK_TYPE_WRAP);
712     if (GSS_ERROR(major))
713         return major;
714
715     if (chanBindings != GSS_C_NO_CHANNEL_BINDINGS &&
716         !bufferEqual(&iov[0].buffer, &chanBindings->application_data)) {
717         major = GSS_S_BAD_BINDINGS;
718         *minor = GSSEAP_BINDINGS_MISMATCH;
719     } else {
720         major = GSS_S_CONTINUE_NEEDED;
721         *minor = 0;
722     }
723
724     gss_release_buffer(&tmpMinor, &iov[0].buffer);
725
726     return major;
727 }
728
729 #ifdef GSSEAP_ENABLE_REAUTH
730 static OM_uint32
731 eapGssSmAcceptReauthCreds(OM_uint32 *minor,
732                           gss_cred_id_t cred,
733                           gss_ctx_id_t ctx,
734                           gss_name_t target GSSEAP_UNUSED,
735                           gss_OID mech GSSEAP_UNUSED,
736                           OM_uint32 reqFlags GSSEAP_UNUSED,
737                           OM_uint32 timeReq GSSEAP_UNUSED,
738                           gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
739                           gss_buffer_t inputToken GSSEAP_UNUSED,
740                           gss_buffer_t outputToken,
741                           OM_uint32 *smFlags GSSEAP_UNUSED)
742 {
743     OM_uint32 major;
744
745     /*
746      * If we're built with fast reauthentication enabled, then
747      * fabricate a ticket from the initiator to ourselves.
748      */
749     if (ctx->flags & CTX_FLAG_KRB_REAUTH_SUPPORTED)
750         major = gssEapMakeReauthCreds(minor, ctx, cred, outputToken);
751     else
752         major = GSS_S_UNAVAILABLE;
753
754     if (major == GSS_S_UNAVAILABLE)
755         major = GSS_S_COMPLETE;
756
757     return GSS_ERROR(major) ? major : GSS_S_CONTINUE_NEEDED;
758 }
759 #endif
760
761 static OM_uint32
762 eapGssSmAcceptInitiatorMIC(OM_uint32 *minor,
763                            gss_cred_id_t cred GSSEAP_UNUSED,
764                            gss_ctx_id_t ctx,
765                            gss_name_t target GSSEAP_UNUSED,
766                            gss_OID mech GSSEAP_UNUSED,
767                            OM_uint32 reqFlags GSSEAP_UNUSED,
768                            OM_uint32 timeReq GSSEAP_UNUSED,
769                            gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
770                            gss_buffer_t inputToken,
771                            gss_buffer_t outputToken GSSEAP_UNUSED,
772                            OM_uint32 *smFlags GSSEAP_UNUSED)
773 {
774     OM_uint32 major;
775
776     assert((ctx->flags & CTX_FLAG_KRB_REAUTH) == 0);
777
778     major = gssEapVerifyConversationMIC(minor, ctx, inputToken);
779     if (GSS_ERROR(major))
780         return major;
781
782     GSSEAP_SM_TRANSITION_NEXT(ctx);
783
784     *minor = 0;
785
786     return GSS_S_CONTINUE_NEEDED;
787 }
788
789 static OM_uint32
790 eapGssSmAcceptAcceptorMIC(OM_uint32 *minor,
791                           gss_cred_id_t cred GSSEAP_UNUSED,
792                           gss_ctx_id_t ctx,
793                           gss_name_t target GSSEAP_UNUSED,
794                           gss_OID mech GSSEAP_UNUSED,
795                           OM_uint32 reqFlags GSSEAP_UNUSED,
796                           OM_uint32 timeReq GSSEAP_UNUSED,
797                           gss_channel_bindings_t chanBindings GSSEAP_UNUSED,
798                           gss_buffer_t inputToken GSSEAP_UNUSED,
799                           gss_buffer_t outputToken,
800                           OM_uint32 *smFlags)
801 {
802     OM_uint32 major;
803
804     major = gssEapGetConversationMIC(minor, ctx, outputToken);
805     if (GSS_ERROR(major))
806         return major;
807
808     GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_ESTABLISHED);
809
810     *minor = 0;
811     *smFlags |= SM_FLAG_SEND_TOKEN | SM_FLAG_OUTPUT_TOKEN_CRITICAL;
812
813     return GSS_S_COMPLETE;
814 }
815
816 /*
817  * Acceptor state machine.
818  */
819 static struct gss_eap_sm eapGssAcceptorSm[] = {
820 #ifdef GSSEAP_ENABLE_REAUTH
821     {
822         ITOK_TYPE_REAUTH_REQ,
823         ITOK_TYPE_REAUTH_RESP,
824         GSSEAP_STATE_INITIAL | GSSEAP_STATE_REAUTHENTICATE,
825         0,
826         eapGssSmAcceptGssReauth,
827     },
828 #endif
829     {
830         ITOK_TYPE_ACCEPTOR_NAME_REQ,
831         ITOK_TYPE_ACCEPTOR_NAME_RESP,
832         GSSEAP_STATE_INITIAL,
833         0,
834         eapGssSmAcceptAcceptorName
835     },
836     {
837         ITOK_TYPE_SUPPORTED_ACCEPTOR_EXTS,
838         ITOK_TYPE_SUPPORTED_INITIATOR_EXTS,
839         GSSEAP_STATE_INITIAL,
840         0,
841         eapGssSmAcceptExts,
842     },
843 #ifdef GSSEAP_DEBUG
844     {
845         ITOK_TYPE_VENDOR_INFO,
846         ITOK_TYPE_NONE,
847         GSSEAP_STATE_INITIAL,
848         0,
849         eapGssSmAcceptVendorInfo,
850     },
851 #endif
852     {
853         ITOK_TYPE_NONE,
854         ITOK_TYPE_EAP_REQ,
855         GSSEAP_STATE_INITIAL,
856         SM_ITOK_FLAG_REQUIRED,
857         eapGssSmAcceptIdentity,
858     },
859     {
860         ITOK_TYPE_EAP_RESP,
861         ITOK_TYPE_EAP_REQ,
862         GSSEAP_STATE_AUTHENTICATE,
863         SM_ITOK_FLAG_REQUIRED,
864         eapGssSmAcceptAuthenticate
865     },
866     {
867         ITOK_TYPE_GSS_FLAGS,
868         ITOK_TYPE_NONE,
869         GSSEAP_STATE_INITIATOR_EXTS,
870         0,
871         eapGssSmAcceptGssFlags
872     },
873     {
874         ITOK_TYPE_GSS_CHANNEL_BINDINGS,
875         ITOK_TYPE_NONE,
876         GSSEAP_STATE_INITIATOR_EXTS,
877         0,
878         eapGssSmAcceptGssChannelBindings,
879     },
880     {
881         ITOK_TYPE_INITIATOR_MIC,
882         ITOK_TYPE_NONE,
883         GSSEAP_STATE_INITIATOR_EXTS,
884         SM_ITOK_FLAG_REQUIRED,
885         eapGssSmAcceptInitiatorMIC,
886     },
887 #ifdef GSSEAP_ENABLE_REAUTH
888     {
889         ITOK_TYPE_NONE,
890         ITOK_TYPE_REAUTH_CREDS,
891         GSSEAP_STATE_ACCEPTOR_EXTS,
892         0,
893         eapGssSmAcceptReauthCreds,
894     },
895 #endif
896     {
897         ITOK_TYPE_NONE,
898         ITOK_TYPE_ACCEPTOR_MIC,
899         GSSEAP_STATE_ACCEPTOR_EXTS,
900         0,
901         eapGssSmAcceptAcceptorMIC
902     },
903 };
904
905 OM_uint32
906 gss_accept_sec_context(OM_uint32 *minor,
907                        gss_ctx_id_t *context_handle,
908                        gss_cred_id_t cred,
909                        gss_buffer_t input_token,
910                        gss_channel_bindings_t input_chan_bindings,
911                        gss_name_t *src_name,
912                        gss_OID *mech_type,
913                        gss_buffer_t output_token,
914                        OM_uint32 *ret_flags,
915                        OM_uint32 *time_rec,
916                        gss_cred_id_t *delegated_cred_handle)
917 {
918     OM_uint32 major, tmpMinor;
919     gss_ctx_id_t ctx = *context_handle;
920
921     *minor = 0;
922
923     output_token->length = 0;
924     output_token->value = NULL;
925
926     if (src_name != NULL)
927         *src_name = GSS_C_NO_NAME;
928
929     if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
930         *minor = GSSEAP_TOK_TRUNC;
931         return GSS_S_DEFECTIVE_TOKEN;
932     }
933
934     if (ctx == GSS_C_NO_CONTEXT) {
935         major = gssEapAllocContext(minor, &ctx);
936         if (GSS_ERROR(major))
937             return major;
938
939         *context_handle = ctx;
940     }
941
942     GSSEAP_MUTEX_LOCK(&ctx->mutex);
943
944     if (cred == GSS_C_NO_CREDENTIAL) {
945         if (ctx->defaultCred == GSS_C_NO_CREDENTIAL) {
946             major = gssEapAcquireCred(minor,
947                                       GSS_C_NO_NAME,
948                                       GSS_C_NO_BUFFER,
949                                       GSS_C_INDEFINITE,
950                                       GSS_C_NO_OID_SET,
951                                       GSS_C_ACCEPT,
952                                       &ctx->defaultCred,
953                                       NULL,
954                                       NULL);
955             if (GSS_ERROR(major))
956                 goto cleanup;
957         }
958
959         cred = ctx->defaultCred;
960     }
961
962     GSSEAP_MUTEX_LOCK(&cred->mutex);
963
964     if (cred->name != GSS_C_NO_NAME) {
965         major = gssEapDuplicateName(minor, cred->name, &ctx->acceptorName);
966         if (GSS_ERROR(major))
967             goto cleanup;
968     }
969
970     major = gssEapSmStep(minor,
971                          cred,
972                          ctx,
973                          GSS_C_NO_NAME,
974                          GSS_C_NO_OID,
975                          0,
976                          GSS_C_INDEFINITE,
977                          input_chan_bindings,
978                          input_token,
979                          output_token,
980                          eapGssAcceptorSm,
981                          sizeof(eapGssAcceptorSm) / sizeof(eapGssAcceptorSm[0]));
982     if (GSS_ERROR(major))
983         goto cleanup;
984
985     if (mech_type != NULL) {
986         OM_uint32 tmpMajor;
987
988         tmpMajor = gssEapCanonicalizeOid(&tmpMinor, ctx->mechanismUsed, 0, mech_type);
989         if (GSS_ERROR(tmpMajor)) {
990             major = tmpMajor;
991             *minor = tmpMinor;
992             goto cleanup;
993         }
994     }
995     if (ret_flags != NULL)
996         *ret_flags = ctx->gssFlags;
997     if (delegated_cred_handle != NULL)
998         *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
999
1000     if (major == GSS_S_COMPLETE) {
1001         if (src_name != NULL && ctx->initiatorName != GSS_C_NO_NAME) {
1002             major = gssEapDuplicateName(&tmpMinor, ctx->initiatorName, src_name);
1003             if (GSS_ERROR(major))
1004                 goto cleanup;
1005         }
1006         if (time_rec != NULL) {
1007             major = gssEapContextTime(&tmpMinor, ctx, time_rec);
1008             if (GSS_ERROR(major))
1009                 goto cleanup;
1010         }
1011     }
1012
1013     assert(CTX_IS_ESTABLISHED(ctx) || major == GSS_S_CONTINUE_NEEDED);
1014
1015 cleanup:
1016     if (cred != GSS_C_NO_CREDENTIAL)
1017         GSSEAP_MUTEX_UNLOCK(&cred->mutex);
1018     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
1019
1020     if (GSS_ERROR(major))
1021         gssEapReleaseContext(&tmpMinor, context_handle);
1022
1023     return major;
1024 }
1025
1026 #ifdef GSSEAP_ENABLE_REAUTH
1027 static OM_uint32
1028 acceptReadyKrb(OM_uint32 *minor,
1029                gss_ctx_id_t ctx,
1030                gss_cred_id_t cred,
1031                const gss_name_t initiator,
1032                const gss_OID mech,
1033                OM_uint32 timeRec)
1034 {
1035     OM_uint32 major;
1036
1037     major = gssEapGlueToMechName(minor, ctx, initiator, &ctx->initiatorName);
1038     if (GSS_ERROR(major))
1039         return major;
1040
1041     major = gssEapReauthComplete(minor, ctx, cred, mech, timeRec);
1042     if (GSS_ERROR(major))
1043         return major;
1044
1045     *minor = 0;
1046     return GSS_S_COMPLETE;
1047 }
1048
1049 static OM_uint32
1050 eapGssSmAcceptGssReauth(OM_uint32 *minor,
1051                         gss_cred_id_t cred,
1052                         gss_ctx_id_t ctx,
1053                         gss_name_t target GSSEAP_UNUSED,
1054                         gss_OID mech,
1055                         OM_uint32 reqFlags GSSEAP_UNUSED,
1056                         OM_uint32 timeReq GSSEAP_UNUSED,
1057                         gss_channel_bindings_t userChanBindings,
1058                         gss_buffer_t inputToken,
1059                         gss_buffer_t outputToken,
1060                         OM_uint32 *smFlags)
1061 {
1062     OM_uint32 major, tmpMinor;
1063     gss_name_t krbInitiator = GSS_C_NO_NAME;
1064     OM_uint32 gssFlags, timeRec = GSS_C_INDEFINITE;
1065     struct gss_channel_bindings_struct wireChanBindings = { 0 };
1066
1067     /*
1068      * If we're built with fast reauthentication support, it's valid
1069      * for an initiator to send a GSS reauthentication token as its
1070      * initial context token, causing us to short-circuit the state
1071      * machine and process Kerberos GSS messages instead.
1072      */
1073
1074     ctx->flags |= CTX_FLAG_KRB_REAUTH;
1075
1076     /*
1077      * To avoid an additional round trip, we use GSS channel bindings
1078      * to integrity protect the rest of the initiator exchange. This
1079      * does have the disadvantage of making it impossible for the
1080      * acceptor to ignore application channel bindings, behaviour
1081      * which differs from normal Kerberos and GSS-EAP itself.
1082      */
1083     major = gssEapMakeTokenChannelBindings(minor, ctx,
1084                                            userChanBindings,
1085                                            inputToken,
1086                                            &wireChanBindings);
1087     if (GSS_ERROR(major))
1088         return major;
1089
1090     major = gssAcceptSecContext(minor,
1091                                 &ctx->kerberosCtx,
1092                                 cred->krbCred,
1093                                 inputToken,
1094                                 &wireChanBindings,
1095                                 &krbInitiator,
1096                                 &mech,
1097                                 outputToken,
1098                                 &gssFlags,
1099                                 &timeRec,
1100                                 NULL);
1101     if (major == GSS_S_COMPLETE) {
1102         major = acceptReadyKrb(minor, ctx, cred,
1103                                krbInitiator, mech, timeRec);
1104         if (major == GSS_S_COMPLETE) {
1105             /* Generate acceptor MIC */
1106             GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_ACCEPTOR_EXTS);
1107         }
1108         ctx->gssFlags = gssFlags;
1109     } else if (GSS_ERROR(major) &&
1110         (*smFlags & SM_FLAG_INPUT_TOKEN_CRITICAL) == 0) {
1111         /* Fall back to EAP */
1112         gssDeleteSecContext(&tmpMinor, &ctx->kerberosCtx, GSS_C_NO_BUFFER);
1113         ctx->flags &= ~(CTX_FLAG_KRB_REAUTH);
1114         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_INITIAL);
1115     } else {
1116         GSSEAP_SM_TRANSITION(ctx, GSSEAP_STATE_REAUTHENTICATE);
1117     }
1118
1119     major = GSS_S_CONTINUE_NEEDED;
1120
1121     gssReleaseName(&tmpMinor, &krbInitiator);
1122     gss_release_buffer(&tmpMinor, &wireChanBindings.application_data);
1123
1124     return major;
1125 }
1126 #endif /* GSSEAP_ENABLE_REAUTH */