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