Merge remote-tracking branch 'origin/eap-tls'
[mech_eap.git] / mech_eap / util.h
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  * Portions Copyright 2003-2010 Massachusetts Institute of Technology.
34  * All Rights Reserved.
35  *
36  * Export of this software from the United States of America may
37  *   require a specific license from the United States Government.
38  *   It is the responsibility of any person or organization contemplating
39  *   export to obtain such a license before exporting.
40  *
41  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
42  * distribute this software and its documentation for any purpose and
43  * without fee is hereby granted, provided that the above copyright
44  * notice appear in all copies and that both that copyright notice and
45  * this permission notice appear in supporting documentation, and that
46  * the name of M.I.T. not be used in advertising or publicity pertaining
47  * to distribution of the software without specific, written prior
48  * permission.  Furthermore if you modify this software you must label
49  * your software as modified software and not distribute it in such a
50  * fashion that it might be confused with the original M.I.T. software.
51  * M.I.T. makes no representations about the suitability of
52  * this software for any purpose.  It is provided "as is" without express
53  * or implied warranty.
54  *
55  */
56
57 /*
58  * Utility functions.
59  */
60
61 #ifndef _UTIL_H_
62 #define _UTIL_H_ 1
63
64 #ifdef HAVE_SYS_PARAM_H
65 #include <sys/param.h>
66 #endif
67 #ifdef HAVE_STDINT_H
68 #include <stdint.h>
69 #endif
70 #include <string.h>
71 #include <errno.h>
72
73 #include <krb5.h>
74
75 #ifdef WIN32
76 # ifndef __cplusplus
77 # define inline __inline
78 # endif
79 #define snprintf _snprintf
80 #endif
81
82 #ifdef __cplusplus
83 extern "C" {
84 #endif
85
86 #ifndef MIN
87 #define MIN(_a,_b)  ((_a)<(_b)?(_a):(_b))
88 #endif
89
90 #if !defined(WIN32) && !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
91 #define GSSEAP_UNUSED __attribute__ ((__unused__))
92 #else
93 #define GSSEAP_UNUSED
94 #endif
95
96 /* util_buffer.c */
97 OM_uint32
98 makeStringBuffer(OM_uint32 *minor,
99                  const char *string,
100                  gss_buffer_t buffer);
101
102 #define makeStringBufferOrCleanup(src, dst)             \
103     do {                                                \
104         major = makeStringBuffer((minor), (src), (dst));\
105         if (GSS_ERROR(major))                           \
106             goto cleanup;                               \
107     } while (0)
108
109 OM_uint32
110 bufferToString(OM_uint32 *minor,
111                const gss_buffer_t buffer,
112                char **pString);
113
114 OM_uint32
115 duplicateBuffer(OM_uint32 *minor,
116                 const gss_buffer_t src,
117                 gss_buffer_t dst);
118
119 #define duplicateBufferOrCleanup(src, dst)              \
120     do {                                                \
121         major = duplicateBuffer((minor), (src), (dst)); \
122         if (GSS_ERROR(major))                           \
123             goto cleanup;                               \
124     } while (0)
125
126 static inline int
127 bufferEqual(const gss_buffer_t b1, const gss_buffer_t b2)
128 {
129     return (b1->length == b2->length &&
130             memcmp(b1->value, b2->value, b2->length) == 0);
131 }
132
133 static inline int
134 bufferEqualString(const gss_buffer_t b1, const char *s)
135 {
136     gss_buffer_desc b2;
137
138     b2.length = strlen(s);
139     b2.value = (char *)s;
140
141     return bufferEqual(b1, &b2);
142 }
143
144 /* util_cksum.c */
145 int
146 gssEapSign(krb5_context context,
147            krb5_cksumtype type,
148            size_t rrc,
149 #ifdef HAVE_HEIMDAL_VERSION
150            krb5_crypto crypto,
151 #else
152            krb5_keyblock *key,
153 #endif
154            krb5_keyusage sign_usage,
155            gss_iov_buffer_desc *iov,
156            int iov_count);
157
158 int
159 gssEapVerify(krb5_context context,
160              krb5_cksumtype type,
161              size_t rrc,
162 #ifdef HAVE_HEIMDAL_VERSION
163              krb5_crypto crypto,
164 #else
165              krb5_keyblock *key,
166 #endif
167              krb5_keyusage sign_usage,
168              gss_iov_buffer_desc *iov,
169              int iov_count,
170              int *valid);
171
172 #if 0
173 OM_uint32
174 gssEapEncodeGssChannelBindings(OM_uint32 *minor,
175                                gss_channel_bindings_t chanBindings,
176                                gss_buffer_t encodedBindings);
177 #endif
178
179 /* util_context.c */
180 #define EAP_EXPORT_CONTEXT_V1           1
181
182 enum gss_eap_token_type {
183     TOK_TYPE_NONE                    = 0x0000,  /* no token */
184     TOK_TYPE_MIC                     = 0x0404,  /* RFC 4121 MIC token */
185     TOK_TYPE_WRAP                    = 0x0504,  /* RFC 4121 wrap token */
186     TOK_TYPE_EXPORT_NAME             = 0x0401,  /* RFC 2743 exported name */
187     TOK_TYPE_EXPORT_NAME_COMPOSITE   = 0x0402,  /* exported composite name */
188     TOK_TYPE_DELETE_CONTEXT          = 0x0405,  /* RFC 2743 delete context */
189     TOK_TYPE_INITIATOR_CONTEXT       = 0x0601,  /* initiator-sent context token */
190     TOK_TYPE_ACCEPTOR_CONTEXT        = 0x0602,  /* acceptor-sent context token */
191 };
192
193 /* inner token types and flags */
194 #define ITOK_TYPE_NONE                  0x00000000
195 #define ITOK_TYPE_CONTEXT_ERR           0x00000001 /* critical */
196 #define ITOK_TYPE_ACCEPTOR_NAME_REQ     0x00000002 /* TBD */
197 #define ITOK_TYPE_ACCEPTOR_NAME_RESP    0x00000003 /* TBD */
198 #define ITOK_TYPE_EAP_RESP              0x00000004 /* critical, required, if not reauth */
199 #define ITOK_TYPE_EAP_REQ               0x00000005 /* critical, required, if not reauth */
200 #define ITOK_TYPE_GSS_CHANNEL_BINDINGS  0x00000006 /* critical, required, if not reauth */
201 #define ITOK_TYPE_REAUTH_CREDS          0x00000007 /* optional */
202 #define ITOK_TYPE_REAUTH_REQ            0x00000008 /* optional */
203 #define ITOK_TYPE_REAUTH_RESP           0x00000009 /* optional */
204 #define ITOK_TYPE_VERSION_INFO          0x0000000A /* optional */
205 #define ITOK_TYPE_VENDOR_INFO           0x0000000B /* optional */
206 #define ITOK_TYPE_GSS_FLAGS             0x0000000C /* optional */
207 #define ITOK_TYPE_INITIATOR_MIC         0x0000000D /* critical, required, if not reauth */
208 #define ITOK_TYPE_ACCEPTOR_MIC          0x0000000E /* TBD */
209
210 #define ITOK_FLAG_CRITICAL              0x80000000  /* critical, wire flag */
211 #define ITOK_FLAG_VERIFIED              0x40000000  /* verified, API flag */
212
213 #define ITOK_TYPE_MASK                  (~(ITOK_FLAG_CRITICAL | ITOK_FLAG_VERIFIED))
214
215 #define GSSEAP_WIRE_FLAGS_MASK          ( GSS_C_MUTUAL_FLAG             | \
216                                           GSS_C_DCE_STYLE               | \
217                                           GSS_C_IDENTIFY_FLAG           | \
218                                           GSS_C_EXTENDED_ERROR_FLAG       )
219
220 OM_uint32 gssEapAllocContext(OM_uint32 *minor, gss_ctx_id_t *pCtx);
221 OM_uint32 gssEapReleaseContext(OM_uint32 *minor, gss_ctx_id_t *pCtx);
222
223 OM_uint32
224 gssEapMakeToken(OM_uint32 *minor,
225                 gss_ctx_id_t ctx,
226                 const gss_buffer_t innerToken,
227                 enum gss_eap_token_type tokenType,
228                 gss_buffer_t outputToken);
229
230 OM_uint32
231 gssEapVerifyToken(OM_uint32 *minor,
232                   gss_ctx_id_t ctx,
233                   const gss_buffer_t inputToken,
234                   enum gss_eap_token_type *tokenType,
235                   gss_buffer_t innerInputToken);
236
237 OM_uint32
238 gssEapContextTime(OM_uint32 *minor,
239                   gss_ctx_id_t context_handle,
240                   OM_uint32 *time_rec);
241
242 OM_uint32
243 gssEapMakeTokenMIC(OM_uint32 *minor,
244                    gss_ctx_id_t ctx,
245                    gss_buffer_t tokenMIC);
246
247 OM_uint32
248 gssEapVerifyTokenMIC(OM_uint32 *minor,
249                      gss_ctx_id_t ctx,
250                      const gss_buffer_t tokenMIC);
251
252 /* util_cred.c */
253 OM_uint32 gssEapAllocCred(OM_uint32 *minor, gss_cred_id_t *pCred);
254 OM_uint32 gssEapReleaseCred(OM_uint32 *minor, gss_cred_id_t *pCred);
255
256 gss_OID
257 gssEapPrimaryMechForCred(gss_cred_id_t cred);
258
259 OM_uint32
260 gssEapAcquireCred(OM_uint32 *minor,
261                   const gss_name_t desiredName,
262                   OM_uint32 timeReq,
263                   const gss_OID_set desiredMechs,
264                   int cred_usage,
265                   gss_cred_id_t *pCred,
266                   gss_OID_set *pActualMechs,
267                   OM_uint32 *timeRec);
268
269 OM_uint32
270 gssEapSetCredPassword(OM_uint32 *minor,
271                       gss_cred_id_t cred,
272                       const gss_buffer_t password);
273
274 OM_uint32
275 gssEapSetCredClientCertificate(OM_uint32 *minor,
276                                gss_cred_id_t cred,
277                                const gss_buffer_t clientCert,
278                                const gss_buffer_t privateKey);
279
280 OM_uint32
281 gssEapSetCredService(OM_uint32 *minor,
282                      gss_cred_id_t cred,
283                      const gss_name_t target);
284
285 OM_uint32
286 gssEapResolveInitiatorCred(OM_uint32 *minor,
287                            const gss_cred_id_t cred,
288                            const gss_name_t target,
289                            gss_cred_id_t *resolvedCred);
290
291 int gssEapCredAvailable(gss_cred_id_t cred, gss_OID mech);
292
293 OM_uint32
294 gssEapInquireCred(OM_uint32 *minor,
295                   gss_cred_id_t cred,
296                   gss_name_t *name,
297                   OM_uint32 *pLifetime,
298                   gss_cred_usage_t *cred_usage,
299                   gss_OID_set *mechanisms);
300
301 /* util_crypt.c */
302 int
303 gssEapEncrypt(krb5_context context, int dce_style, size_t ec,
304               size_t rrc,
305 #ifdef HAVE_HEIMDAL_VERSION
306               krb5_crypto crypto,
307 #else
308               krb5_keyblock *key,
309 #endif
310               int usage,
311               gss_iov_buffer_desc *iov, int iov_count);
312
313 int
314 gssEapDecrypt(krb5_context context, int dce_style, size_t ec,
315               size_t rrc,
316 #ifdef HAVE_HEIMDAL_VERSION
317               krb5_crypto crypto,
318 #else
319               krb5_keyblock *key,
320 #endif
321               int usage,
322               gss_iov_buffer_desc *iov, int iov_count);
323
324 int
325 gssEapMapCryptoFlag(OM_uint32 type);
326
327 gss_iov_buffer_t
328 gssEapLocateIov(gss_iov_buffer_desc *iov,
329                 int iov_count,
330                 OM_uint32 type);
331
332 void
333 gssEapIovMessageLength(gss_iov_buffer_desc *iov,
334                        int iov_count,
335                        size_t *data_length,
336                        size_t *assoc_data_length);
337
338 void
339 gssEapReleaseIov(gss_iov_buffer_desc *iov, int iov_count);
340
341 int
342 gssEapIsIntegrityOnly(gss_iov_buffer_desc *iov, int iov_count);
343
344 int
345 gssEapAllocIov(gss_iov_buffer_t iov, size_t size);
346
347 OM_uint32
348 gssEapDeriveRfc3961Key(OM_uint32 *minor,
349                        const unsigned char *key,
350                        size_t keyLength,
351                        krb5_enctype enctype,
352                        krb5_keyblock *pKey);
353
354 /* util_krb.c */
355
356 #ifndef KRB_MALLOC
357 /*
358  * If your Kerberos library uses a different allocator to your
359  * GSS mechanism glue, then you might wish to define these in
360  * config.h or elsewhere. This should eventually go away when
361  * we no longer need to allocate memory that is freed by the
362  * Kerberos library.
363  */
364 #define KRB_CALLOC                      calloc
365 #define KRB_MALLOC                      malloc
366 #define KRB_FREE                        free
367 #define KRB_REALLOC                     realloc
368 #endif /* KRB_MALLOC */
369
370 #ifdef HAVE_HEIMDAL_VERSION
371
372 #define KRB_TIME_FOREVER        ((time_t)~0L)
373
374 #define KRB_KEY_TYPE(key)       ((key)->keytype)
375 #define KRB_KEY_DATA(key)       ((key)->keyvalue.data)
376 #define KRB_KEY_LENGTH(key)     ((key)->keyvalue.length)
377
378 #define KRB_PRINC_LENGTH(princ) ((princ)->name.name_string.len)
379 #define KRB_PRINC_TYPE(princ)   ((princ)->name.name_type)
380 #define KRB_PRINC_NAME(princ)   ((princ)->name.name_string.val)
381 #define KRB_PRINC_REALM(princ)  ((princ)->realm)
382
383 #define KRB_KT_ENT_KEYBLOCK(e)  (&(e)->keyblock)
384 #define KRB_KT_ENT_FREE(c, e)   krb5_kt_free_entry((c), (e))
385
386 #define KRB_CRYPTO_CONTEXT(ctx) (krbCrypto)
387
388 #define KRB_DATA_INIT(d)        krb5_data_zero((d))
389
390 #define KRB_CHECKSUM_TYPE(c)    ((c)->cksumtype)
391 #define KRB_CHECKSUM_LENGTH(c)  ((c)->checksum.length)
392 #define KRB_CHECKSUM_DATA(c)    ((c)->checksum.data)
393
394 #define KRB_CHECKSUM_INIT(cksum, type, d)      do { \
395         (cksum)->cksumtype = (type);                \
396         (cksum)->checksum.length = (d)->length;     \
397         (cksum)->checksum.data = (d)->value;        \
398     } while (0)
399
400 #else
401
402 #define KRB_TIME_FOREVER        KRB5_INT32_MAX
403
404 #define KRB_KEY_TYPE(key)       ((key)->enctype)
405 #define KRB_KEY_DATA(key)       ((key)->contents)
406 #define KRB_KEY_LENGTH(key)     ((key)->length)
407
408 #define KRB_PRINC_LENGTH(princ) (krb5_princ_size(NULL, (princ)))
409 #define KRB_PRINC_TYPE(princ)   (krb5_princ_type(NULL, (princ)))
410 #define KRB_PRINC_NAME(princ)   (krb5_princ_name(NULL, (princ)))
411 #define KRB_PRINC_REALM(princ)  (krb5_princ_realm(NULL, (princ)))
412 #define KRB_PRINC_COMPONENT(princ, component) \
413         (krb5_princ_component(NULL, (princ), (component)))
414
415 #define KRB_KT_ENT_KEYBLOCK(e)  (&(e)->key)
416 #define KRB_KT_ENT_FREE(c, e)   krb5_free_keytab_entry_contents((c), (e))
417
418 #define KRB_CRYPTO_CONTEXT(ctx) (&(ctx)->rfc3961Key)
419
420 #define KRB_DATA_INIT(d)        do {        \
421         (d)->magic = KV5M_DATA;             \
422         (d)->length = 0;                    \
423         (d)->data = NULL;                   \
424     } while (0)
425
426 #define KRB_CHECKSUM_TYPE(c)    ((c)->checksum_type)
427 #define KRB_CHECKSUM_LENGTH(c)  ((c)->length)
428 #define KRB_CHECKSUM_DATA(c)    ((c)->contents)
429
430 #define KRB_CHECKSUM_INIT(cksum, type, d)      do { \
431         (cksum)->checksum_type = (type);            \
432         (cksum)->length = (d)->length;              \
433         (cksum)->contents = (d)->value;             \
434     } while (0)
435
436 #endif /* HAVE_HEIMDAL_VERSION */
437
438 #define KRB_KEY_INIT(key)       do {        \
439         KRB_KEY_TYPE(key) = ENCTYPE_NULL;   \
440         KRB_KEY_DATA(key) = NULL;           \
441         KRB_KEY_LENGTH(key) = 0;            \
442     } while (0)
443
444 #define GSSEAP_KRB_INIT(ctx) do {                   \
445         OM_uint32 tmpMajor;                         \
446                                                     \
447         tmpMajor  = gssEapKerberosInit(minor, ctx); \
448         if (GSS_ERROR(tmpMajor)) {                  \
449             return tmpMajor;                        \
450         }                                           \
451     } while (0)
452
453 OM_uint32
454 gssEapKerberosInit(OM_uint32 *minor, krb5_context *context);
455
456 OM_uint32
457 rfc3961ChecksumTypeForKey(OM_uint32 *minor,
458                           krb5_keyblock *key,
459                           krb5_cksumtype *cksumtype);
460
461 krb5_error_code
462 krbCryptoLength(krb5_context krbContext,
463 #ifdef HAVE_HEIMDAL_VERSION
464                 krb5_crypto krbCrypto,
465 #else
466                 krb5_keyblock *key,
467 #endif
468                 int type,
469                 size_t *length);
470
471 krb5_error_code
472 krbPaddingLength(krb5_context krbContext,
473 #ifdef HAVE_HEIMDAL_VERSION
474                  krb5_crypto krbCrypto,
475 #else
476                  krb5_keyblock *key,
477 #endif
478                  size_t dataLength,
479                  size_t *padLength);
480
481 krb5_error_code
482 krbBlockSize(krb5_context krbContext,
483 #ifdef HAVE_HEIMDAL_VERSION
484                  krb5_crypto krbCrypto,
485 #else
486                  krb5_keyblock *key,
487 #endif
488                  size_t *blockSize);
489
490 krb5_error_code
491 krbEnctypeToString(krb5_context krbContext,
492                    krb5_enctype enctype,
493                    const char *prefix,
494                    gss_buffer_t string);
495
496 krb5_error_code
497 krbMakeAuthDataKdcIssued(krb5_context context,
498                          const krb5_keyblock *key,
499                          krb5_const_principal issuer,
500 #ifdef HAVE_HEIMDAL_VERSION
501                          const AuthorizationData *authdata,
502                          AuthorizationData *adKdcIssued
503 #else
504                          krb5_authdata *const *authdata,
505                          krb5_authdata ***adKdcIssued
506 #endif
507                          );
508
509 krb5_error_code
510 krbMakeCred(krb5_context context,
511             krb5_auth_context authcontext,
512             krb5_creds *creds,
513             krb5_data *data);
514
515 /* util_lucid.c */
516 OM_uint32
517 gssEapExportLucidSecContext(OM_uint32 *minor,
518                             gss_ctx_id_t ctx,
519                             const gss_OID desiredObject,
520                             gss_buffer_set_t *data_set);
521
522 /* util_mech.c */
523 extern gss_OID GSS_EAP_MECHANISM;
524
525 #define OID_FLAG_NULL_VALID                 0x00000001
526 #define OID_FLAG_FAMILY_MECH_VALID          0x00000002
527 #define OID_FLAG_MAP_NULL_TO_DEFAULT_MECH   0x00000004
528 #define OID_FLAG_MAP_FAMILY_MECH_TO_NULL    0x00000008
529
530 OM_uint32
531 gssEapCanonicalizeOid(OM_uint32 *minor,
532                       const gss_OID oid,
533                       OM_uint32 flags,
534                       gss_OID *pOid);
535
536 OM_uint32
537 gssEapReleaseOid(OM_uint32 *minor, gss_OID *oid);
538
539 OM_uint32
540 gssEapDefaultMech(OM_uint32 *minor,
541                   gss_OID *oid);
542
543 OM_uint32
544 gssEapIndicateMechs(OM_uint32 *minor,
545                     gss_OID_set *mechs);
546
547 OM_uint32
548 gssEapEnctypeToOid(OM_uint32 *minor,
549                    krb5_enctype enctype,
550                    gss_OID *pOid);
551
552 OM_uint32
553 gssEapOidToEnctype(OM_uint32 *minor,
554                    const gss_OID oid,
555                    krb5_enctype *enctype);
556
557 int
558 gssEapIsMechanismOid(const gss_OID oid);
559
560 int
561 gssEapIsConcreteMechanismOid(const gss_OID oid);
562
563 OM_uint32
564 gssEapValidateMechs(OM_uint32 *minor,
565                    const gss_OID_set mechs);
566
567 gss_buffer_t
568 gssEapOidToSaslName(const gss_OID oid);
569
570 gss_OID
571 gssEapSaslNameToOid(const gss_buffer_t name);
572
573 /* util_moonshot.c */
574 OM_uint32
575 libMoonshotResolveDefaultIdentity(OM_uint32 *minor,
576                                   const gss_cred_id_t cred,
577                                   gss_name_t *pName);
578
579 OM_uint32
580 libMoonshotResolveInitiatorCred(OM_uint32 *minor,
581                                 gss_cred_id_t cred,
582                                 const gss_name_t targetName);
583
584 /* util_name.c */
585 #define EXPORT_NAME_FLAG_OID                    0x1
586 #define EXPORT_NAME_FLAG_COMPOSITE              0x2
587 #define EXPORT_NAME_FLAG_ALLOW_COMPOSITE        0x4
588
589 OM_uint32 gssEapAllocName(OM_uint32 *minor, gss_name_t *pName);
590 OM_uint32 gssEapReleaseName(OM_uint32 *minor, gss_name_t *pName);
591 OM_uint32 gssEapExportName(OM_uint32 *minor,
592                            const gss_name_t name,
593                            gss_buffer_t exportedName);
594 OM_uint32 gssEapExportNameInternal(OM_uint32 *minor,
595                                    const gss_name_t name,
596                                    gss_buffer_t exportedName,
597                                    OM_uint32 flags);
598 OM_uint32 gssEapImportName(OM_uint32 *minor,
599                            const gss_buffer_t input_name_buffer,
600                            const gss_OID input_name_type,
601                            const gss_OID input_mech_type,
602                            gss_name_t *output_name);
603 OM_uint32 gssEapImportNameInternal(OM_uint32 *minor,
604                                    const gss_buffer_t input_name_buffer,
605                                    gss_name_t *output_name,
606                                    OM_uint32 flags);
607 OM_uint32
608 gssEapDuplicateName(OM_uint32 *minor,
609                     const gss_name_t input_name,
610                     gss_name_t *dest_name);
611
612 OM_uint32
613 gssEapCanonicalizeName(OM_uint32 *minor,
614                        const gss_name_t input_name,
615                        const gss_OID mech_type,
616                        gss_name_t *dest_name);
617
618 OM_uint32
619 gssEapDisplayName(OM_uint32 *minor,
620                   gss_name_t name,
621                   gss_buffer_t output_name_buffer,
622                   gss_OID *output_name_type);
623
624 #define COMPARE_NAME_FLAG_IGNORE_EMPTY_REALMS   0x1
625
626 OM_uint32
627 gssEapCompareName(OM_uint32 *minor,
628                   gss_name_t name1,
629                   gss_name_t name2,
630                   OM_uint32 flags,
631                   int *name_equal);
632
633 /* util_oid.c */
634 OM_uint32
635 composeOid(OM_uint32 *minor_status,
636            const char *prefix,
637            size_t prefix_len,
638            int suffix,
639            gss_OID_desc *oid);
640
641 OM_uint32
642 decomposeOid(OM_uint32 *minor_status,
643              const char *prefix,
644              size_t prefix_len,
645              gss_OID_desc *oid,
646              int *suffix) ;
647
648 OM_uint32
649 duplicateOid(OM_uint32 *minor_status,
650              const gss_OID_desc * const oid,
651              gss_OID *new_oid);
652
653 OM_uint32
654 duplicateOidSet(OM_uint32 *minor,
655                 const gss_OID_set src,
656                 gss_OID_set *dst);
657
658 static inline int
659 oidEqual(const gss_OID_desc *o1, const gss_OID_desc *o2)
660 {
661     if (o1 == GSS_C_NO_OID)
662         return (o2 == GSS_C_NO_OID);
663     else if (o2 == GSS_C_NO_OID)
664         return (o1 == GSS_C_NO_OID);
665     else
666         return (o1->length == o2->length &&
667                 memcmp(o1->elements, o2->elements, o1->length) == 0);
668 }
669
670 /* util_ordering.c */
671 OM_uint32
672 sequenceInternalize(OM_uint32 *minor,
673                     void **vqueue,
674                     unsigned char **buf,
675                     size_t *lenremain);
676
677 OM_uint32
678 sequenceExternalize(OM_uint32 *minor,
679                     void *vqueue,
680                     unsigned char **buf,
681                     size_t *lenremain);
682
683 size_t
684 sequenceSize(void *vqueue);
685
686 OM_uint32
687 sequenceFree(OM_uint32 *minor, void **vqueue);
688
689 OM_uint32
690 sequenceCheck(OM_uint32 *minor, void **vqueue, uint64_t seqnum);
691
692 OM_uint32
693 sequenceInit(OM_uint32 *minor, void **vqueue, uint64_t seqnum,
694              int do_replay, int do_sequence, int wide_nums);
695
696 /* util_sm.c */
697 enum gss_eap_state {
698     GSSEAP_STATE_INITIAL        = 0x01,     /* initial state */
699     GSSEAP_STATE_AUTHENTICATE   = 0x02,     /* exchange EAP messages */
700     GSSEAP_STATE_INITIATOR_EXTS = 0x04,     /* initiator extensions */
701     GSSEAP_STATE_ACCEPTOR_EXTS  = 0x08,     /* acceptor extensions */
702 #ifdef GSSEAP_ENABLE_REAUTH
703     GSSEAP_STATE_REAUTHENTICATE = 0x10,     /* GSS reauthentication messages */
704 #endif
705     GSSEAP_STATE_ESTABLISHED    = 0x20,     /* context established */
706     GSSEAP_STATE_ALL            = 0x3F
707 };
708
709 #define GSSEAP_STATE_NEXT(s)    ((s) << 1)
710
711 #define GSSEAP_SM_STATE(ctx)                ((ctx)->state)
712
713 #ifdef GSSEAP_DEBUG
714 void gssEapSmTransition(gss_ctx_id_t ctx, enum gss_eap_state state);
715 #define GSSEAP_SM_TRANSITION(ctx, state)    gssEapSmTransition((ctx), (state))
716 #else
717 #define GSSEAP_SM_TRANSITION(ctx, newstate)    do { (ctx)->state = (newstate); } while (0)
718 #endif
719
720 #define GSSEAP_SM_TRANSITION_NEXT(ctx)      GSSEAP_SM_TRANSITION((ctx), GSSEAP_STATE_NEXT(GSSEAP_SM_STATE((ctx))))
721
722 /* state machine entry */
723 struct gss_eap_sm {
724     OM_uint32 inputTokenType;
725     OM_uint32 outputTokenType;
726     enum gss_eap_state validStates;
727     OM_uint32 itokFlags;
728     OM_uint32 (*processToken)(OM_uint32 *,
729                               gss_cred_id_t,
730                               gss_ctx_id_t,
731                               gss_name_t,
732                               gss_OID,
733                               OM_uint32,
734                               OM_uint32,
735                               gss_channel_bindings_t,
736                               gss_buffer_t,
737                               gss_buffer_t,
738                               OM_uint32 *);
739 };
740
741 /* state machine flags, set by handler */
742 #define SM_FLAG_FORCE_SEND_TOKEN            0x00000001  /* send token even if no inner tokens */
743 #define SM_FLAG_OUTPUT_TOKEN_CRITICAL       0x00000002  /* output token is critical */
744
745 /* state machine flags, set by state machine */
746 #define SM_FLAG_INPUT_TOKEN_CRITICAL        0x10000000  /* input token was critical */
747
748 #define SM_ITOK_FLAG_REQUIRED               0x00000001  /* received tokens must be present */
749
750 OM_uint32
751 gssEapSmStep(OM_uint32 *minor,
752              gss_cred_id_t cred,
753              gss_ctx_id_t ctx,
754              gss_name_t target,
755              gss_OID mech,
756              OM_uint32 reqFlags,
757              OM_uint32 timeReq,
758              gss_channel_bindings_t chanBindings,
759              gss_buffer_t inputToken,
760              gss_buffer_t outputToken,
761              struct gss_eap_sm *sm,
762              size_t smCount);
763
764 void
765 gssEapSmTransition(gss_ctx_id_t ctx, enum gss_eap_state state);
766
767 /* util_token.c */
768 struct gss_eap_token_buffer_set {
769     gss_buffer_set_desc buffers; /* pointers only */
770     OM_uint32 *types;
771 };
772
773 OM_uint32
774 gssEapEncodeInnerTokens(OM_uint32 *minor,
775                         struct gss_eap_token_buffer_set *tokens,
776                         gss_buffer_t buffer);
777 OM_uint32
778 gssEapDecodeInnerTokens(OM_uint32 *minor,
779                         const gss_buffer_t buffer,
780                         struct gss_eap_token_buffer_set *tokens);
781
782 OM_uint32
783 gssEapReleaseInnerTokens(OM_uint32 *minor,
784                          struct gss_eap_token_buffer_set *tokens,
785                          int freeBuffers);
786
787 OM_uint32
788 gssEapAllocInnerTokens(OM_uint32 *minor,
789                        size_t count,
790                        struct gss_eap_token_buffer_set *tokens);
791
792 size_t
793 tokenSize(const gss_OID_desc *mech, size_t body_size);
794
795 void
796 makeTokenHeader(const gss_OID_desc *mech,
797                 size_t body_size,
798                 unsigned char **buf,
799                 enum gss_eap_token_type tok_type);
800
801 OM_uint32
802 verifyTokenHeader(OM_uint32 *minor,
803                   gss_OID mech,
804                   size_t *body_size,
805                   unsigned char **buf_in,
806                   size_t toksize_in,
807                   enum gss_eap_token_type *ret_tok_type);
808
809 /* Helper macros */
810 #ifndef GSSEAP_MALLOC
811 #if _WIN32
812 #include <gssapi/gssapi_alloc.h>
813 #define GSSEAP_MALLOC                   gssalloc_malloc
814 #define GSSEAP_CALLOC                   gssalloc_calloc
815 #define GSSEAP_FREE                     gssalloc_free
816 #define GSSEAP_REALLOC                  gssalloc_realloc
817 #else
818 #define GSSEAP_CALLOC                   calloc
819 #define GSSEAP_MALLOC                   malloc
820 #define GSSEAP_FREE                     free
821 #define GSSEAP_REALLOC                  realloc
822 #endif /* _WIN32 */
823 #endif /* !GSSEAP_MALLOC */
824
825 #ifndef GSSAPI_CALLCONV
826 #define GSSAPI_CALLCONV                 KRB5_CALLCONV
827 #endif
828
829 #ifndef GSSEAP_ASSERT
830 #include <assert.h>
831 #define GSSEAP_ASSERT(x)                assert((x))
832 #endif /* !GSSEAP_ASSERT */
833
834 #ifdef WIN32
835 #define GSSEAP_CONSTRUCTOR
836 #define GSSEAP_DESTRUCTOR
837 #else
838 #define GSSEAP_CONSTRUCTOR              __attribute__((constructor))
839 #define GSSEAP_DESTRUCTOR               __attribute__((destructor))
840 #endif
841
842 #define GSSEAP_NOT_IMPLEMENTED          do {            \
843         GSSEAP_ASSERT(0 && "not implemented");          \
844         *minor = ENOSYS;                                \
845         return GSS_S_FAILURE;                           \
846     } while (0)
847
848 #ifdef WIN32
849
850 #include <winbase.h>
851
852 #define GSSEAP_GET_LAST_ERROR()         (GetLastError()) /* XXX FIXME */
853
854 #define GSSEAP_MUTEX                    CRITICAL_SECTION
855 #define GSSEAP_MUTEX_INIT(m)            (InitializeCriticalSection((m)), 0)
856 #define GSSEAP_MUTEX_DESTROY(m)         DeleteCriticalSection((m))
857 #define GSSEAP_MUTEX_LOCK(m)            EnterCriticalSection((m))
858 #define GSSEAP_MUTEX_UNLOCK(m)          LeaveCriticalSection((m))
859 #define GSSEAP_ONCE_LEAVE               do { return TRUE; } while (0)
860
861 /* Thread-local is handled separately */
862
863 #define GSSEAP_THREAD_ONCE              INIT_ONCE
864 #define GSSEAP_ONCE_CALLBACK(cb)        BOOL CALLBACK cb(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *Context)
865 #define GSSEAP_ONCE(o, i)               InitOnceExecuteOnce((o), (i), NULL, NULL)
866 #define GSSEAP_ONCE_INITIALIZER         INIT_ONCE_STATIC_INIT
867
868 #else
869
870 #include <pthread.h>
871
872 #define GSSEAP_GET_LAST_ERROR()         (errno)
873
874 #define GSSEAP_MUTEX                    pthread_mutex_t
875 #define GSSEAP_MUTEX_INIT(m)            pthread_mutex_init((m), NULL)
876 #define GSSEAP_MUTEX_DESTROY(m)         pthread_mutex_destroy((m))
877 #define GSSEAP_MUTEX_LOCK(m)            pthread_mutex_lock((m))
878 #define GSSEAP_MUTEX_UNLOCK(m)          pthread_mutex_unlock((m))
879
880 #define GSSEAP_THREAD_KEY               pthread_key_t
881 #define GSSEAP_KEY_CREATE(k, d)         pthread_key_create((k), (d))
882 #define GSSEAP_GETSPECIFIC(k)           pthread_getspecific((k))
883 #define GSSEAP_SETSPECIFIC(k, d)        pthread_setspecific((k), (d))
884
885 #define GSSEAP_THREAD_ONCE              pthread_once_t
886 #define GSSEAP_ONCE_CALLBACK(cb)        void cb(void)
887 #define GSSEAP_ONCE(o, i)               pthread_once((o), (i))
888 #define GSSEAP_ONCE_INITIALIZER         PTHREAD_ONCE_INIT
889 #define GSSEAP_ONCE_LEAVE               do { } while (0)
890
891 #endif /* WIN32 */
892
893 /* Helper functions */
894 static inline void
895 store_uint16_be(uint16_t val, void *vp)
896 {
897     unsigned char *p = (unsigned char *)vp;
898
899     p[0] = (val >>  8) & 0xff;
900     p[1] = (val      ) & 0xff;
901 }
902
903 static inline uint16_t
904 load_uint16_be(const void *cvp)
905 {
906     const unsigned char *p = (const unsigned char *)cvp;
907
908     return (p[1] | (p[0] << 8));
909 }
910
911 static inline void
912 store_uint32_be(uint32_t val, void *vp)
913 {
914     unsigned char *p = (unsigned char *)vp;
915
916     p[0] = (val >> 24) & 0xff;
917     p[1] = (val >> 16) & 0xff;
918     p[2] = (val >>  8) & 0xff;
919     p[3] = (val      ) & 0xff;
920 }
921
922 static inline uint32_t
923 load_uint32_be(const void *cvp)
924 {
925     const unsigned char *p = (const unsigned char *)cvp;
926
927     return (p[3] | (p[2] << 8)
928             | ((uint32_t) p[1] << 16)
929             | ((uint32_t) p[0] << 24));
930 }
931
932 static inline void
933 store_uint64_be(uint64_t val, void *vp)
934 {
935     unsigned char *p = (unsigned char *)vp;
936
937     p[0] = (unsigned char)((val >> 56) & 0xff);
938     p[1] = (unsigned char)((val >> 48) & 0xff);
939     p[2] = (unsigned char)((val >> 40) & 0xff);
940     p[3] = (unsigned char)((val >> 32) & 0xff);
941     p[4] = (unsigned char)((val >> 24) & 0xff);
942     p[5] = (unsigned char)((val >> 16) & 0xff);
943     p[6] = (unsigned char)((val >>  8) & 0xff);
944     p[7] = (unsigned char)((val      ) & 0xff);
945 }
946
947 static inline uint64_t
948 load_uint64_be(const void *cvp)
949 {
950     const unsigned char *p = (const unsigned char *)cvp;
951
952     return ((uint64_t)load_uint32_be(p) << 32) | load_uint32_be(p + 4);
953 }
954
955 static inline unsigned char *
956 store_buffer(gss_buffer_t buffer, void *vp, int wide_nums)
957 {
958     unsigned char *p = (unsigned char *)vp;
959
960     if (wide_nums) {
961         store_uint64_be(buffer->length, p);
962         p += 8;
963     } else {
964         store_uint32_be(buffer->length, p);
965         p += 4;
966     }
967
968     if (buffer->value != NULL) {
969         memcpy(p, buffer->value, buffer->length);
970         p += buffer->length;
971     }
972
973     return p;
974 }
975
976 static inline unsigned char *
977 load_buffer(const void *cvp, size_t length, gss_buffer_t buffer)
978 {
979     buffer->length = 0;
980     buffer->value = GSSEAP_MALLOC(length);
981     if (buffer->value == NULL)
982         return NULL;
983     buffer->length = length;
984     memcpy(buffer->value, cvp, length);
985     return (unsigned char *)cvp + length;
986 }
987
988 static inline unsigned char *
989 store_oid(gss_OID oid, void *vp)
990 {
991     gss_buffer_desc buf;
992
993     if (oid != GSS_C_NO_OID) {
994         buf.length = oid->length;
995         buf.value = oid->elements;
996     } else {
997         buf.length = 0;
998         buf.value = NULL;
999     }
1000
1001     return store_buffer(&buf, vp, FALSE);
1002 }
1003
1004 static inline void
1005 krbDataToGssBuffer(krb5_data *data, gss_buffer_t buffer)
1006 {
1007     buffer->value = (void *)data->data;
1008     buffer->length = data->length;
1009 }
1010
1011 static inline void
1012 krbPrincComponentToGssBuffer(krb5_principal krbPrinc,
1013                              int index, gss_buffer_t buffer)
1014 {
1015     if (KRB_PRINC_LENGTH(krbPrinc) < index) {
1016         buffer->value = NULL;
1017         buffer->length = 0;
1018     } else {
1019 #ifdef HAVE_HEIMDAL_VERSION
1020         buffer->value = (void *)KRB_PRINC_NAME(krbPrinc)[index];
1021         buffer->length = strlen((char *)buffer->value);
1022 #else
1023         buffer->value = (void *)krb5_princ_component(NULL, krbPrinc, index)->data;
1024         buffer->length = krb5_princ_component(NULL, krbPrinc, index)->length;
1025 #endif /* HAVE_HEIMDAL_VERSION */
1026     }
1027 }
1028
1029 static inline krb5_error_code
1030 krbPrincUnparseServiceSpecifics(krb5_context krbContext, krb5_principal krbPrinc,
1031                                 gss_buffer_t nameBuf)
1032 {
1033     krb5_error_code result = 0;
1034     if (KRB_PRINC_LENGTH(krbPrinc) > 2) {
1035         /* Acceptor-Service-Specific */
1036         krb5_principal_data ssiPrinc = *krbPrinc;
1037         char *ssi;
1038
1039         KRB_PRINC_LENGTH(&ssiPrinc) -= 2;
1040         KRB_PRINC_NAME(&ssiPrinc) += 2;
1041
1042         result = krb5_unparse_name_flags(krbContext, &ssiPrinc,
1043                                          KRB5_PRINCIPAL_UNPARSE_NO_REALM, &ssi);
1044         if (result != 0)
1045             return result;
1046
1047         nameBuf->value = ssi;
1048         nameBuf->length = strlen(ssi);
1049     } else {
1050         nameBuf->value = NULL;
1051         nameBuf->length = 0;
1052     }
1053
1054     return result;
1055 }
1056
1057 static inline void
1058 krbFreeUnparsedName(krb5_context krbContext, gss_buffer_t nameBuf)
1059 {
1060 #ifdef HAVE_HEIMDAL_VERSION
1061     krb5_xfree((char *) nameBuf->value);
1062 #else
1063     krb5_free_unparsed_name(krbContext, (char *)(nameBuf->value));
1064 #endif
1065     nameBuf->value = NULL;
1066     nameBuf->length = 0;
1067 }
1068
1069 static inline void
1070 krbPrincRealmToGssBuffer(krb5_principal krbPrinc, gss_buffer_t buffer)
1071 {
1072 #ifdef HAVE_HEIMDAL_VERSION
1073     buffer->value = (void *)KRB_PRINC_REALM(krbPrinc);
1074     buffer->length = strlen((char *)buffer->value);
1075 #else
1076     krbDataToGssBuffer(KRB_PRINC_REALM(krbPrinc), buffer);
1077 #endif
1078 }
1079
1080 static inline void
1081 gssBufferToKrbData(gss_buffer_t buffer, krb5_data *data)
1082 {
1083     data->data = (char *)buffer->value;
1084     data->length = buffer->length;
1085 }
1086
1087 /* util_tld.c */
1088 struct gss_eap_status_info;
1089
1090 struct gss_eap_thread_local_data {
1091     krb5_context krbContext;
1092     struct gss_eap_status_info *statusInfo;
1093 };
1094
1095 struct gss_eap_thread_local_data *
1096 gssEapGetThreadLocalData(void);
1097
1098 void
1099 gssEapDestroyStatusInfo(struct gss_eap_status_info *status);
1100
1101 void
1102 gssEapDestroyKrbContext(krb5_context context);
1103
1104 #ifdef __cplusplus
1105 }
1106 #endif
1107
1108 #ifdef GSSEAP_ENABLE_ACCEPTOR
1109 #include "util_json.h"
1110 #include "util_attr.h"
1111 #include "util_base64.h"
1112 #endif /* GSSEAP_ENABLE_ACCEPTOR */
1113 #ifdef GSSEAP_ENABLE_REAUTH
1114 #include "util_reauth.h"
1115 #endif
1116
1117 #endif /* _UTIL_H_ */