4d6891886241cf1b6a88bd8e15c0972c833c6b28
[mech_eap.git] / accept_sec_context.c
1 /*
2  * Copyright (c) 2010, 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 #include "gssapiP_eap.h"
34
35 #ifdef BUILTIN_EAP
36 #define EAP_KEY_AVAILABLE(ctx)  ((ctx)->acceptorCtx.eapPolInterface->eapKeyAvailable)
37 #define EAP_KEY_DATA(ctx)       ((ctx)->acceptorCtx.eapPolInterface->eapKeyData)
38 #define EAP_KEY_LENGTH(ctx)     ((ctx)->acceptorCtx.eapPolInterface->eapKeyDataLen)
39 #else
40 #define EAP_KEY_AVAILABLE(ctx)  0
41 #define EAP_KEY_DATA(ctx)       NULL
42 #define EAP_KEY_LENGTH(ctx)     0
43 #endif /* BUILTIN_EAP */
44
45 static OM_uint32
46 acceptReady(OM_uint32 *minor, gss_ctx_id_t ctx);
47
48 #ifdef BUILTIN_EAP
49 #define EAP_MAX_METHODS 8
50
51 #define EAP_TTLS_AUTH_PAP 1
52 #define EAP_TTLS_AUTH_CHAP 2
53 #define EAP_TTLS_AUTH_MSCHAP 4
54 #define EAP_TTLS_AUTH_MSCHAPV2 8
55
56 struct eap_user {
57         struct {
58                 int vendor;
59                 u32 method;
60         } methods[EAP_MAX_METHODS];
61         u8 *password;
62         size_t password_len;
63         int password_hash; /* whether password is hashed with
64                             * nt_password_hash() */
65         int phase2;
66         int force_version;
67         int ttls_auth; /* bitfield of
68                         * EAP_TTLS_AUTH_{PAP,CHAP,MSCHAP,MSCHAPV2} */
69 };
70
71 struct eap_eapol_interface {
72         /* Lower layer to full authenticator variables */
73         Boolean eapResp; /* shared with EAPOL Backend Authentication */
74         struct wpabuf *eapRespData;
75         Boolean portEnabled;
76         int retransWhile;
77         Boolean eapRestart; /* shared with EAPOL Authenticator PAE */
78         int eapSRTT;
79         int eapRTTVAR;
80
81         /* Full authenticator to lower layer variables */
82         Boolean eapReq; /* shared with EAPOL Backend Authentication */
83         Boolean eapNoReq; /* shared with EAPOL Backend Authentication */
84         Boolean eapSuccess;
85         Boolean eapFail;
86         Boolean eapTimeout;
87         struct wpabuf *eapReqData;
88         u8 *eapKeyData;
89         size_t eapKeyDataLen;
90         Boolean eapKeyAvailable; /* called keyAvailable in IEEE 802.1X-2004 */
91
92         /* AAA interface to full authenticator variables */
93         Boolean aaaEapReq;
94         Boolean aaaEapNoReq;
95         Boolean aaaSuccess;
96         Boolean aaaFail;
97         struct wpabuf *aaaEapReqData;
98         u8 *aaaEapKeyData;
99         size_t aaaEapKeyDataLen;
100         Boolean aaaEapKeyAvailable;
101         int aaaMethodTimeout;
102
103         /* Full authenticator to AAA interface variables */
104         Boolean aaaEapResp;
105         struct wpabuf *aaaEapRespData;
106         /* aaaIdentity -> eap_get_identity() */
107         Boolean aaaTimeout;
108 };
109
110 #define eapol_callbacks     SERVER_eapol_callbacks
111
112 struct eapol_callbacks {
113         int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
114                             int phase2, struct eap_user *user);
115         const char * (*get_eap_req_id_text)(void *ctx, size_t *len);
116 };
117
118 #define eap_config          SERVER_eap_config
119
120 struct eap_config {
121         void *ssl_ctx;
122         void *msg_ctx;
123         void *eap_sim_db_priv;
124         Boolean backend_auth;
125         int eap_server;
126         u8 *pac_opaque_encr_key;
127         u8 *eap_fast_a_id;
128         size_t eap_fast_a_id_len;
129         char *eap_fast_a_id_info;
130         int eap_fast_prov;
131         int pac_key_lifetime;
132         int pac_key_refresh_time;
133         int eap_sim_aka_result_ind;
134         int tnc;
135         struct wps_context *wps;
136         const struct wpabuf *assoc_wps_ie;
137         const u8 *peer_addr;
138         int fragment_size;
139 };
140
141 struct eap_sm * eap_server_sm_init(void *eapol_ctx,
142                                    struct eapol_callbacks *eapol_cb,
143                                    struct eap_config *eap_conf);
144 void eap_server_sm_deinit(struct eap_sm *sm);
145 int eap_server_sm_step(struct eap_sm *sm);
146 void eap_sm_notify_cached(struct eap_sm *sm);
147 void eap_sm_pending_cb(struct eap_sm *sm);
148 int eap_sm_method_pending(struct eap_sm *sm);
149 const u8 * eap_get_identity(struct eap_sm *sm, size_t *len);
150 struct eap_eapol_interface * eap_get_interface(struct eap_sm *sm);
151
152 #include <eap_server/eap_i.h>
153
154 static OM_uint32
155 initTls(OM_uint32 *minor,
156         gss_ctx_id_t ctx)
157 {
158     struct tls_config tconf;
159     struct tls_connection_params tparams;
160
161     memset(&tconf, 0, sizeof(tconf));
162     ctx->acceptorCtx.tlsContext = tls_init(&tconf);
163     if (ctx->acceptorCtx.tlsContext == NULL)
164         return GSS_S_FAILURE;
165
166     memset(&tparams, 0, sizeof(tparams));
167     tparams.ca_cert = "ca.pem";
168     tparams.client_cert = "server.pem";
169     tparams.private_key = "server-key.pem";
170
171     if (tls_global_set_params(ctx->acceptorCtx.tlsContext, &tparams)) {
172         return GSS_S_FAILURE;
173     }
174
175     if (tls_global_set_verify(ctx->acceptorCtx.tlsContext, 0)) {
176         return GSS_S_FAILURE;
177     }
178
179     return GSS_S_COMPLETE;
180 }
181
182 static int
183 serverGetEapUser(void *ctx,
184                  const unsigned char *identity,
185                  size_t identityLength,
186                  int phase2,
187                  struct eap_user *user)
188 {
189     gss_ctx_id_t gssCtx = (gss_ctx_id_t)ctx;
190     OM_uint32 major, minor;
191     gss_buffer_desc buf;
192
193     memset(user, 0, sizeof(*user));
194
195     buf.length = identityLength;
196     buf.value = (void *)identity;
197
198     if (phase2 == 0) {
199         user->methods[0].vendor = EAP_VENDOR_IETF;
200         user->methods[0].method = EAP_TYPE_PEAP;
201         return 0;
202     }
203
204     major = gssEapImportName(&minor, &buf, GSS_C_NT_USER_NAME,
205                              &gssCtx->initiatorName);
206     if (GSS_ERROR(major))
207         return -1;
208
209     /*
210      * OK, obviously there is no real security here, this is simply
211      * for testing the token exchange; this code will be completely
212      * replaced with libradsec once that library is available.
213      */
214     user->methods[0].vendor = EAP_VENDOR_IETF;
215     user->methods[0].method = EAP_TYPE_MSCHAPV2;
216     user->password = (unsigned char *)strdup(" ");
217     user->password_len = 1;
218
219     return 0;
220 }
221
222 static const char *
223 serverGetEapReqIdText(void *ctx,
224                       size_t *len)
225 {
226     *len = 0;
227     return NULL;
228 }
229
230 static OM_uint32
231 eapGssSmAcceptAuthenticate(OM_uint32 *minor,
232                            gss_ctx_id_t ctx,
233                            gss_cred_id_t cred,
234                            gss_buffer_t inputToken,
235                            gss_channel_bindings_t chanBindings,
236                            gss_buffer_t outputToken)
237 {
238     OM_uint32 major;
239     OM_uint32 tmpMinor, tmpMajor;
240     int code;
241     struct wpabuf respData;
242     static struct eapol_callbacks cb = { serverGetEapUser, serverGetEapReqIdText };
243     if (ctx->acceptorCtx.eap == NULL) {
244         struct eap_config eapConfig;
245
246         major = initTls(minor, ctx);
247         if (GSS_ERROR(major))
248             goto cleanup;
249
250         memset(&eapConfig, 0, sizeof(eapConfig));
251         eapConfig.eap_server = 1;
252         eapConfig.ssl_ctx = ctx->acceptorCtx.tlsContext;
253
254         ctx->acceptorCtx.eap = eap_server_sm_init(ctx, &cb, &eapConfig);
255         if (ctx->acceptorCtx.eap == NULL) {
256             major = GSS_S_FAILURE;
257             goto cleanup;
258         }
259
260         ctx->acceptorCtx.eapPolInterface = eap_get_interface(ctx->acceptorCtx.eap);
261         ctx->acceptorCtx.eapPolInterface->portEnabled = TRUE;
262         ctx->acceptorCtx.eapPolInterface->eapRestart = TRUE;
263     }
264
265     if (ctx->acceptorName == GSS_C_NO_NAME &&
266         cred != GSS_C_NO_CREDENTIAL &&
267         cred->name != GSS_C_NO_NAME) {
268         major = gss_duplicate_name(minor, cred->name, &ctx->acceptorName);
269         if (GSS_ERROR(major))
270             goto cleanup;
271     }
272
273     wpabuf_set(&respData, inputToken->value, inputToken->length);
274     ctx->acceptorCtx.eapPolInterface->eapRespData = &respData;
275     ctx->acceptorCtx.eapPolInterface->eapResp = TRUE;
276
277     code = eap_server_sm_step(ctx->acceptorCtx.eap);
278
279     if (ctx->acceptorCtx.eapPolInterface->eapReq) {
280         ctx->acceptorCtx.eapPolInterface->eapReq = 0;
281         major = GSS_S_CONTINUE_NEEDED;
282     }
283
284     if (ctx->acceptorCtx.eapPolInterface->eapSuccess) {
285         ctx->acceptorCtx.eapPolInterface->eapSuccess = 0;
286         major = acceptReady(minor, ctx);
287         if (GSS_ERROR(major))
288             goto cleanup;
289
290         ctx->state = EAP_STATE_GSS_CHANNEL_BINDINGS;
291         major = GSS_S_CONTINUE_NEEDED;
292     } else if (ctx->acceptorCtx.eapPolInterface->eapFail) {
293         ctx->acceptorCtx.eapPolInterface->eapFail = 0;
294         major = GSS_S_FAILURE;
295     } else if (code == 0) {
296         major = GSS_S_FAILURE;
297     }
298
299     if (ctx->acceptorCtx.eapPolInterface->eapReqData != NULL) {
300         gss_buffer_desc buf;
301
302         buf.length = wpabuf_len(ctx->acceptorCtx.eapPolInterface->eapReqData);
303         buf.value = (void *)wpabuf_head(ctx->acceptorCtx.eapPolInterface->eapReqData);
304
305         tmpMajor = duplicateBuffer(&tmpMinor, &buf, outputToken);
306         if (GSS_ERROR(tmpMajor)) {
307             major = tmpMajor;
308             *minor = tmpMinor;
309             goto cleanup;
310         }
311     }
312
313 cleanup:
314     ctx->acceptorCtx.eapPolInterface->eapRespData = NULL;
315
316     return major;
317 }
318 #else
319 static OM_uint32
320 eapGssSmAcceptAuthenticate(OM_uint32 *minor,
321                            gss_ctx_id_t ctx,
322                            gss_cred_id_t cred,
323                            gss_buffer_t inputToken,
324                            gss_channel_bindings_t chanBindings,
325                            gss_buffer_t outputToken)
326 {
327     OM_uint32 major, tmpMinor;
328
329 cleanup:
330     return major;
331 }
332 #endif /* BUILTIN_EAP */
333
334 static OM_uint32
335 eapGssSmAcceptGssChannelBindings(OM_uint32 *minor,
336                                  gss_ctx_id_t ctx,
337                                  gss_cred_id_t cred,
338                                  gss_buffer_t inputToken,
339                                  gss_channel_bindings_t chanBindings,
340                                  gss_buffer_t outputToken)
341 {
342     OM_uint32 major, tmpMinor;
343     gss_iov_buffer_desc iov[2];
344
345     outputToken->length = 0;
346     outputToken->value = NULL;
347
348     if (chanBindings == GSS_C_NO_CHANNEL_BINDINGS) {
349         ctx->state = EAP_STATE_ESTABLISHED;
350         return GSS_S_COMPLETE;
351     }
352
353     if (inputToken->length < 14) {
354         return GSS_S_DEFECTIVE_TOKEN;
355     }
356
357     iov[0].type = GSS_IOV_BUFFER_TYPE_DATA;
358     iov[0].buffer.length = 0;
359     iov[0].buffer.value = NULL;
360
361     if (chanBindings != GSS_C_NO_CHANNEL_BINDINGS)
362         iov[0].buffer = chanBindings->application_data;
363
364     iov[1].type = GSS_IOV_BUFFER_TYPE_HEADER;
365     iov[1].buffer.length = 16;
366     iov[1].buffer.value = (unsigned char *)inputToken->value - 2;
367
368     assert(load_uint16_be(iov[1].buffer.value) == TOK_TYPE_GSS_CB);
369
370     iov[2].type = GSS_IOV_BUFFER_TYPE_TRAILER;
371     iov[2].buffer.length = inputToken->length - 14;
372     iov[2].buffer.value = (unsigned char *)inputToken->value + 14;
373
374     major = gssEapUnwrapOrVerifyMIC(minor, ctx, NULL, NULL,
375                                     iov, 3, TOK_TYPE_GSS_CB);
376     if (major == GSS_S_COMPLETE) {
377         ctx->state = EAP_STATE_ESTABLISHED;
378     }
379
380 #if 0
381     gss_release_buffer(&tmpMinor, &iov[0].buffer);
382 #endif
383
384     return major;
385 }
386
387 static OM_uint32
388 eapGssSmAcceptEstablished(OM_uint32 *minor,
389                           gss_ctx_id_t ctx,
390                           gss_cred_id_t cred,
391                           gss_buffer_t inputToken,
392                           gss_channel_bindings_t chanBindings,
393                           gss_buffer_t outputToken)
394 {
395     /* Called with already established context */
396     *minor = EINVAL;
397     return GSS_S_BAD_STATUS;
398 }
399
400 static struct eap_gss_acceptor_sm {
401     enum gss_eap_token_type inputTokenType;
402     enum gss_eap_token_type outputTokenType;
403     OM_uint32 (*processToken)(OM_uint32 *,
404                               gss_ctx_id_t,
405                               gss_cred_id_t,
406                               gss_buffer_t,
407                               gss_channel_bindings_t,
408                               gss_buffer_t);
409 } eapGssAcceptorSm[] = {
410     { TOK_TYPE_EAP_RESP,    TOK_TYPE_EAP_REQ,  eapGssSmAcceptAuthenticate       },
411 #if 0
412     { TOK_TYPE_EAP_RESP,    TOK_TYPE_EAP_REQ,  NULL                             },
413     { TOK_TYPE_EAP_RESP,    TOK_TYPE_EAP_REQ,  NULL                             },
414 #endif
415     { TOK_TYPE_GSS_CB,      TOK_TYPE_NONE,     eapGssSmAcceptGssChannelBindings },
416     { TOK_TYPE_NONE,        TOK_TYPE_NONE,     eapGssSmAcceptEstablished        },
417 };
418
419 OM_uint32
420 gss_accept_sec_context(OM_uint32 *minor,
421                        gss_ctx_id_t *context_handle,
422                        gss_cred_id_t cred,
423                        gss_buffer_t input_token,
424                        gss_channel_bindings_t input_chan_bindings,
425                        gss_name_t *src_name,
426                        gss_OID *mech_type,
427                        gss_buffer_t output_token,
428                        OM_uint32 *ret_flags,
429                        OM_uint32 *time_rec,
430                        gss_cred_id_t *delegated_cred_handle)
431 {
432     OM_uint32 major;
433     OM_uint32 tmpMajor, tmpMinor;
434     gss_ctx_id_t ctx = *context_handle;
435     struct eap_gss_acceptor_sm *sm = NULL;
436     gss_buffer_desc innerInputToken, innerOutputToken;
437
438     *minor = 0;
439
440     innerOutputToken.length = 0;
441     innerOutputToken.value = NULL;
442
443     output_token->length = 0;
444     output_token->value = NULL;
445
446     if (cred != GSS_C_NO_CREDENTIAL && !(cred->flags & CRED_FLAG_ACCEPT)) {
447         return GSS_S_NO_CRED;
448     }
449
450     if (input_token == GSS_C_NO_BUFFER || input_token->length == 0) {
451         return GSS_S_DEFECTIVE_TOKEN;
452     }
453
454     if (ctx == GSS_C_NO_CONTEXT) {
455         major = gssEapAllocContext(minor, &ctx);
456         if (GSS_ERROR(major))
457             return major;
458
459         *context_handle = ctx;
460     }
461
462     GSSEAP_MUTEX_LOCK(&ctx->mutex);
463
464     sm = &eapGssAcceptorSm[ctx->state];
465
466     major = gssEapVerifyToken(minor, ctx, input_token,
467                               sm->inputTokenType, &innerInputToken);
468     if (GSS_ERROR(major))
469         goto cleanup;
470
471     /* If credentials were provided, check they're usable with this mech */
472     if (!gssEapCredAvailable(cred, ctx->mechanismUsed)) {
473         major = GSS_S_BAD_MECH;
474         goto cleanup;
475     }
476
477     do {
478         sm = &eapGssAcceptorSm[ctx->state];
479
480         major = (sm->processToken)(minor,
481                                    ctx,
482                                    cred,
483                                    &innerInputToken,
484                                    input_chan_bindings,
485                                    &innerOutputToken);
486         if (GSS_ERROR(major))
487             goto cleanup;
488     } while (major == GSS_S_CONTINUE_NEEDED && innerOutputToken.length == 0);
489
490     if (mech_type != NULL) {
491         if (!gssEapInternalizeOid(ctx->mechanismUsed, mech_type))
492             duplicateOid(&tmpMinor, ctx->mechanismUsed, mech_type);
493     }
494     if (innerOutputToken.length != 0) {
495         tmpMajor = gssEapMakeToken(&tmpMinor, ctx, &innerOutputToken,
496                                    sm->outputTokenType, output_token);
497         if (GSS_ERROR(tmpMajor)) {
498             major = tmpMajor;
499             *minor = tmpMinor;
500             goto cleanup;
501         }
502     }
503     if (ret_flags != NULL)
504         *ret_flags = ctx->gssFlags;
505     if (delegated_cred_handle != NULL)
506         *delegated_cred_handle = GSS_C_NO_CREDENTIAL;
507
508     if (major == GSS_S_COMPLETE) {
509         if (src_name != NULL && ctx->initiatorName != GSS_C_NO_NAME) {
510             major = gss_duplicate_name(&tmpMinor, ctx->initiatorName, src_name);
511             if (GSS_ERROR(major))
512                 goto cleanup;
513         }
514         if (time_rec != NULL)
515             gss_context_time(&tmpMinor, ctx, time_rec);
516     }
517
518     assert(ctx->state == EAP_STATE_ESTABLISHED || major == GSS_S_CONTINUE_NEEDED);
519
520 cleanup:
521     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
522
523     if (GSS_ERROR(major))
524         gssEapReleaseContext(&tmpMinor, context_handle);
525
526     gss_release_buffer(&tmpMinor, &innerOutputToken);
527
528     return major;
529 }
530
531 /*
532  * Mark a context as ready for cryptographic operations
533  */
534 static OM_uint32
535 acceptReady(OM_uint32 *minor, gss_ctx_id_t ctx)
536 {
537     OM_uint32 major;
538
539     /* Cache encryption type derived from selected mechanism OID */
540     major = gssEapOidToEnctype(minor, ctx->mechanismUsed, &ctx->encryptionType);
541     if (GSS_ERROR(major))
542         return major;
543
544     if (ctx->encryptionType != ENCTYPE_NULL &&
545         EAP_KEY_AVAILABLE(ctx)) {
546         major = gssEapDeriveRfc3961Key(minor,
547                                        EAP_KEY_DATA(ctx),
548                                        EAP_KEY_LENGTH(ctx),
549                                        ctx->encryptionType,
550                                        &ctx->rfc3961Key);
551         if (GSS_ERROR(major))
552             return major;
553
554         major = rfc3961ChecksumTypeForKey(minor, &ctx->rfc3961Key,
555                                            &ctx->checksumType);
556         if (GSS_ERROR(major))
557             return major;
558     } else {
559         /*
560          * draft-howlett-eap-gss says that integrity/confidentialty should
561          * always be advertised as available, but if we have no keying
562          * material it seems confusing to the caller to advertise this.
563          */
564         ctx->gssFlags &= ~(GSS_C_INTEG_FLAG | GSS_C_CONF_FLAG);
565     }
566
567     major = sequenceInit(minor,
568                          &ctx->seqState, ctx->recvSeq,
569                          ((ctx->gssFlags & GSS_C_REPLAY_FLAG) != 0),
570                          ((ctx->gssFlags & GSS_C_SEQUENCE_FLAG) != 0),
571                          TRUE);
572     if (GSS_ERROR(major))
573         return major;
574
575     return GSS_S_COMPLETE;
576 }