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