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