]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/bind9/lib/dns/spnego.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / bind9 / lib / dns / spnego.c
1 /*
2  * Copyright (C) 2006-2011  Internet Systems Consortium, Inc. ("ISC")
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
9  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
11  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
13  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14  * PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 /* $Id: spnego.c,v 1.16.10.2 2011-04-04 11:10:57 marka Exp $ */
18
19 /*! \file
20  * \brief
21  * Portable SPNEGO implementation.
22  *
23  * This is part of a portable implementation of the SPNEGO protocol
24  * (RFCs 2478 and 4178).  This implementation uses the RFC 4178 ASN.1
25  * module but is not a full implementation of the RFC 4178 protocol;
26  * at the moment, we only support GSS-TSIG with Kerberos
27  * authentication, so we only need enough of the SPNEGO protocol to
28  * support that.
29  *
30  * The files that make up this portable SPNEGO implementation are:
31  * \li  spnego.c        (this file)
32  * \li  spnego.h        (API SPNEGO exports to the rest of lib/dns)
33  * \li  spnego.asn1     (SPNEGO ASN.1 module)
34  * \li  spnego_asn1.c   (routines generated from spngo.asn1)
35  * \li  spnego_asn1.pl  (perl script to generate spnego_asn1.c)
36  *
37  * Everything but the functions exported in spnego.h is static, to
38  * avoid possible conflicts with other libraries (particularly Heimdal,
39  * since much of this code comes from Heimdal by way of mod_auth_kerb).
40  *
41  * spnego_asn1.c is shipped as part of lib/dns because generating it
42  * requires both Perl and the Heimdal ASN.1 compiler.  See
43  * spnego_asn1.pl for further details.  We've tried to eliminate all
44  * compiler warnings from the generated code, but you may see a few
45  * when using a compiler version we haven't tested yet.
46  */
47
48 /*
49  * Portions of this code were derived from mod_auth_kerb and Heimdal.
50  * These packages are available from:
51  *
52  *   http://modauthkerb.sourceforge.net/
53  *   http://www.pdc.kth.se/heimdal/
54  *
55  * and were released under the following licenses:
56  *
57  * ----------------------------------------------------------------
58  *
59  * Copyright (c) 2004 Masarykova universita
60  * (Masaryk University, Brno, Czech Republic)
61  * All rights reserved.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions are met:
65  *
66  * 1. Redistributions of source code must retain the above copyright notice,
67  *    this list of conditions and the following disclaimer.
68  *
69  * 2. Redistributions in binary form must reproduce the above copyright
70  *    notice, this list of conditions and the following disclaimer in the
71  *    documentation and/or other materials provided with the distribution.
72  *
73  * 3. Neither the name of the University nor the names of its contributors may
74  *    be used to endorse or promote products derived from this software
75  *    without specific prior written permission.
76  *
77  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
78  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
81  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
82  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
83  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
84  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
85  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
86  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
87  * POSSIBILITY OF SUCH DAMAGE.
88  *
89  * ----------------------------------------------------------------
90  *
91  * Copyright (c) 1997 - 2003 Kungliga Tekniska Högskolan
92  * (Royal Institute of Technology, Stockholm, Sweden).
93  * All rights reserved.
94  *
95  * Redistribution and use in source and binary forms, with or without
96  * modification, are permitted provided that the following conditions
97  * are met:
98  *
99  * 1. Redistributions of source code must retain the above copyright
100  *    notice, this list of conditions and the following disclaimer.
101  *
102  * 2. Redistributions in binary form must reproduce the above copyright
103  *    notice, this list of conditions and the following disclaimer in the
104  *    documentation and/or other materials provided with the distribution.
105  *
106  * 3. Neither the name of the Institute nor the names of its contributors
107  *    may be used to endorse or promote products derived from this software
108  *    without specific prior written permission.
109  *
110  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
111  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
112  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
113  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
114  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
115  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
116  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
117  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
118  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
119  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
120  * SUCH DAMAGE.
121  */
122
123 /*
124  * XXXSRA We should omit this file entirely in Makefile.in via autoconf,
125  * but this will keep it from generating errors until that's written.
126  */
127
128 #ifdef GSSAPI
129
130 /*
131  * XXXSRA Some of the following files are almost certainly unnecessary,
132  * but using this list (borrowed from gssapictx.c) gets rid of some
133  * whacky compilation errors when building with MSVC and should be
134  * harmless in any case.
135  */
136
137 #include <config.h>
138
139 #include <stdlib.h>
140 #include <errno.h>
141
142 #include <isc/buffer.h>
143 #include <isc/dir.h>
144 #include <isc/entropy.h>
145 #include <isc/lex.h>
146 #include <isc/mem.h>
147 #include <isc/once.h>
148 #include <isc/random.h>
149 #include <isc/string.h>
150 #include <isc/time.h>
151 #include <isc/util.h>
152
153 #include <dns/fixedname.h>
154 #include <dns/name.h>
155 #include <dns/rdata.h>
156 #include <dns/rdataclass.h>
157 #include <dns/result.h>
158 #include <dns/types.h>
159 #include <dns/keyvalues.h>
160 #include <dns/log.h>
161
162 #include <dst/gssapi.h>
163 #include <dst/result.h>
164
165 #include "dst_internal.h"
166
167 /*
168  * The API we export
169  */
170 #include "spnego.h"
171
172 /* asn1_err.h */
173 /* Generated from ../../../lib/asn1/asn1_err.et */
174
175 #ifndef ERROR_TABLE_BASE_asn1
176 /* these may be brought in already via gssapi_krb5.h */
177 typedef enum asn1_error_number {
178         ASN1_BAD_TIMEFORMAT = 1859794432,
179         ASN1_MISSING_FIELD = 1859794433,
180         ASN1_MISPLACED_FIELD = 1859794434,
181         ASN1_TYPE_MISMATCH = 1859794435,
182         ASN1_OVERFLOW = 1859794436,
183         ASN1_OVERRUN = 1859794437,
184         ASN1_BAD_ID = 1859794438,
185         ASN1_BAD_LENGTH = 1859794439,
186         ASN1_BAD_FORMAT = 1859794440,
187         ASN1_PARSE_ERROR = 1859794441
188 } asn1_error_number;
189
190 #define ERROR_TABLE_BASE_asn1 1859794432
191 #endif
192
193 #define __asn1_common_definitions__
194
195 typedef struct octet_string {
196         size_t length;
197         void *data;
198 } octet_string;
199
200 typedef char *general_string;
201
202 typedef char *utf8_string;
203
204 typedef struct oid {
205         size_t length;
206         unsigned *components;
207 } oid;
208
209 /* der.h */
210
211 typedef enum {
212         ASN1_C_UNIV = 0, ASN1_C_APPL = 1,
213         ASN1_C_CONTEXT = 2, ASN1_C_PRIVATE = 3
214 } Der_class;
215
216 typedef enum {
217         PRIM = 0, CONS = 1
218 } Der_type;
219
220 /* Universal tags */
221
222 enum {
223         UT_Boolean = 1,
224         UT_Integer = 2,
225         UT_BitString = 3,
226         UT_OctetString = 4,
227         UT_Null = 5,
228         UT_OID = 6,
229         UT_Enumerated = 10,
230         UT_Sequence = 16,
231         UT_Set = 17,
232         UT_PrintableString = 19,
233         UT_IA5String = 22,
234         UT_UTCTime = 23,
235         UT_GeneralizedTime = 24,
236         UT_VisibleString = 26,
237         UT_GeneralString = 27
238 };
239
240 #define ASN1_INDEFINITE 0xdce0deed
241
242 static int
243 der_get_length(const unsigned char *p, size_t len,
244                size_t * val, size_t * size);
245
246 static int
247 der_get_octet_string(const unsigned char *p, size_t len,
248                      octet_string * data, size_t * size);
249 static int
250 der_get_oid(const unsigned char *p, size_t len,
251             oid * data, size_t * size);
252 static int
253 der_get_tag(const unsigned char *p, size_t len,
254             Der_class * class, Der_type * type,
255             int *tag, size_t * size);
256
257 static int
258 der_match_tag(const unsigned char *p, size_t len,
259               Der_class class, Der_type type,
260               int tag, size_t * size);
261 static int
262 der_match_tag_and_length(const unsigned char *p, size_t len,
263                          Der_class class, Der_type type, int tag,
264                          size_t * length_ret, size_t * size);
265
266 static int
267 decode_oid(const unsigned char *p, size_t len,
268            oid * k, size_t * size);
269
270 static int
271 decode_enumerated(const unsigned char *p, size_t len, void *num, size_t *size);
272
273 static int
274 decode_octet_string(const unsigned char *, size_t, octet_string *, size_t *);
275
276 static int
277 der_put_int(unsigned char *p, size_t len, int val, size_t *);
278
279 static int
280 der_put_length(unsigned char *p, size_t len, size_t val, size_t *);
281
282 static int
283 der_put_octet_string(unsigned char *p, size_t len,
284                      const octet_string * data, size_t *);
285 static int
286 der_put_oid(unsigned char *p, size_t len,
287             const oid * data, size_t * size);
288 static int
289 der_put_tag(unsigned char *p, size_t len, Der_class class, Der_type type,
290             int tag, size_t *);
291 static int
292 der_put_length_and_tag(unsigned char *, size_t, size_t,
293                        Der_class, Der_type, int, size_t *);
294
295 static int
296 encode_enumerated(unsigned char *p, size_t len, const void *data, size_t *);
297
298 static int
299 encode_octet_string(unsigned char *p, size_t len,
300                     const octet_string * k, size_t *);
301 static int
302 encode_oid(unsigned char *p, size_t len,
303            const oid * k, size_t *);
304
305 static void
306 free_octet_string(octet_string * k);
307
308 static void
309 free_oid  (oid * k);
310
311 static size_t
312 length_len(size_t len);
313
314 static int
315 fix_dce(size_t reallen, size_t * len);
316
317 /*
318  * Include stuff generated by the ASN.1 compiler.
319  */
320
321 #include "spnego_asn1.c"
322
323 static unsigned char gss_krb5_mech_oid_bytes[] = {
324         0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02
325 };
326
327 static gss_OID_desc gss_krb5_mech_oid_desc = {
328         sizeof(gss_krb5_mech_oid_bytes),
329         gss_krb5_mech_oid_bytes
330 };
331
332 static gss_OID GSS_KRB5_MECH = &gss_krb5_mech_oid_desc;
333
334 static unsigned char gss_mskrb5_mech_oid_bytes[] = {
335         0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02
336 };
337
338 static gss_OID_desc gss_mskrb5_mech_oid_desc = {
339         sizeof(gss_mskrb5_mech_oid_bytes),
340         gss_mskrb5_mech_oid_bytes
341 };
342
343 static gss_OID GSS_MSKRB5_MECH = &gss_mskrb5_mech_oid_desc;
344
345 static unsigned char gss_spnego_mech_oid_bytes[] = {
346         0x2b, 0x06, 0x01, 0x05, 0x05, 0x02
347 };
348
349 static gss_OID_desc gss_spnego_mech_oid_desc = {
350         sizeof(gss_spnego_mech_oid_bytes),
351         gss_spnego_mech_oid_bytes
352 };
353
354 static gss_OID GSS_SPNEGO_MECH = &gss_spnego_mech_oid_desc;
355
356 /* spnegokrb5_locl.h */
357
358 static OM_uint32
359 gssapi_spnego_encapsulate(OM_uint32 *,
360                           unsigned char *,
361                           size_t,
362                           gss_buffer_t,
363                           const gss_OID);
364
365 static OM_uint32
366 gssapi_spnego_decapsulate(OM_uint32 *,
367                           gss_buffer_t,
368                           unsigned char **,
369                           size_t *,
370                           const gss_OID);
371
372 /* mod_auth_kerb.c */
373
374 static int
375 cmp_gss_type(gss_buffer_t token, gss_OID oid)
376 {
377         unsigned char *p;
378         size_t len;
379
380         if (token->length == 0U)
381                 return (GSS_S_DEFECTIVE_TOKEN);
382
383         p = token->value;
384         if (*p++ != 0x60)
385                 return (GSS_S_DEFECTIVE_TOKEN);
386         len = *p++;
387         if (len & 0x80) {
388                 if ((len & 0x7f) > 4U)
389                         return (GSS_S_DEFECTIVE_TOKEN);
390                 p += len & 0x7f;
391         }
392         if (*p++ != 0x06)
393                 return (GSS_S_DEFECTIVE_TOKEN);
394
395         if (((OM_uint32) *p++) != oid->length)
396                 return (GSS_S_DEFECTIVE_TOKEN);
397
398         return (memcmp(p, oid->elements, oid->length));
399 }
400
401 /* accept_sec_context.c */
402 /*
403  * SPNEGO wrapper for Kerberos5 GSS-API kouril@ics.muni.cz, 2003 (mostly
404  * based on Heimdal code)
405  */
406
407 static OM_uint32
408 code_NegTokenArg(OM_uint32 * minor_status,
409                  const NegTokenResp * resp,
410                  unsigned char **outbuf,
411                  size_t * outbuf_size)
412 {
413         OM_uint32 ret;
414         u_char *buf;
415         size_t buf_size, buf_len = 0;
416
417         buf_size = 1024;
418         buf = malloc(buf_size);
419         if (buf == NULL) {
420                 *minor_status = ENOMEM;
421                 return (GSS_S_FAILURE);
422         }
423         do {
424                 ret = encode_NegTokenResp(buf + buf_size - 1,
425                                           buf_size,
426                                           resp, &buf_len);
427                 if (ret == 0) {
428                         size_t tmp;
429
430                         ret = der_put_length_and_tag(buf + buf_size - buf_len - 1,
431                                                      buf_size - buf_len,
432                                                      buf_len,
433                                                      ASN1_C_CONTEXT,
434                                                      CONS,
435                                                      1,
436                                                      &tmp);
437                         if (ret == 0)
438                                 buf_len += tmp;
439                 }
440                 if (ret) {
441                         if (ret == ASN1_OVERFLOW) {
442                                 u_char *tmp;
443
444                                 buf_size *= 2;
445                                 tmp = realloc(buf, buf_size);
446                                 if (tmp == NULL) {
447                                         *minor_status = ENOMEM;
448                                         free(buf);
449                                         return (GSS_S_FAILURE);
450                                 }
451                                 buf = tmp;
452                         } else {
453                                 *minor_status = ret;
454                                 free(buf);
455                                 return (GSS_S_FAILURE);
456                         }
457                 }
458         } while (ret == ASN1_OVERFLOW);
459
460         *outbuf = malloc(buf_len);
461         if (*outbuf == NULL) {
462                 *minor_status = ENOMEM;
463                 free(buf);
464                 return (GSS_S_FAILURE);
465         }
466         memcpy(*outbuf, buf + buf_size - buf_len, buf_len);
467         *outbuf_size = buf_len;
468
469         free(buf);
470
471         return (GSS_S_COMPLETE);
472 }
473
474 static OM_uint32
475 send_reject(OM_uint32 * minor_status,
476             gss_buffer_t output_token)
477 {
478         NegTokenResp resp;
479         OM_uint32 ret;
480
481         resp.negState = malloc(sizeof(*resp.negState));
482         if (resp.negState == NULL) {
483                 *minor_status = ENOMEM;
484                 return (GSS_S_FAILURE);
485         }
486         *(resp.negState) = reject;
487
488         resp.supportedMech = NULL;
489         resp.responseToken = NULL;
490         resp.mechListMIC = NULL;
491
492         ret = code_NegTokenArg(minor_status, &resp,
493                                (unsigned char **)&output_token->value,
494                                &output_token->length);
495         free_NegTokenResp(&resp);
496         if (ret)
497                 return (ret);
498
499         return (GSS_S_BAD_MECH);
500 }
501
502 static OM_uint32
503 send_accept(OM_uint32 * minor_status,
504             gss_buffer_t output_token,
505             gss_buffer_t mech_token,
506             const gss_OID pref)
507 {
508         NegTokenResp resp;
509         OM_uint32 ret;
510
511         memset(&resp, 0, sizeof(resp));
512         resp.negState = malloc(sizeof(*resp.negState));
513         if (resp.negState == NULL) {
514                 *minor_status = ENOMEM;
515                 return (GSS_S_FAILURE);
516         }
517         *(resp.negState) = accept_completed;
518
519         resp.supportedMech = malloc(sizeof(*resp.supportedMech));
520         if (resp.supportedMech == NULL) {
521                 free_NegTokenResp(&resp);
522                 *minor_status = ENOMEM;
523                 return (GSS_S_FAILURE);
524         }
525         ret = der_get_oid(pref->elements,
526                           pref->length,
527                           resp.supportedMech,
528                           NULL);
529         if (ret) {
530                 free_NegTokenResp(&resp);
531                 *minor_status = ENOMEM;
532                 return (GSS_S_FAILURE);
533         }
534         if (mech_token != NULL && mech_token->length != 0U) {
535                 resp.responseToken = malloc(sizeof(*resp.responseToken));
536                 if (resp.responseToken == NULL) {
537                         free_NegTokenResp(&resp);
538                         *minor_status = ENOMEM;
539                         return (GSS_S_FAILURE);
540                 }
541                 resp.responseToken->length = mech_token->length;
542                 resp.responseToken->data = mech_token->value;
543         }
544
545         ret = code_NegTokenArg(minor_status, &resp,
546                                (unsigned char **)&output_token->value,
547                                &output_token->length);
548         if (resp.responseToken != NULL) {
549                 free(resp.responseToken);
550                 resp.responseToken = NULL;
551         }
552         free_NegTokenResp(&resp);
553         if (ret)
554                 return (ret);
555
556         return (GSS_S_COMPLETE);
557 }
558
559 OM_uint32
560 gss_accept_sec_context_spnego(OM_uint32 *minor_status,
561                               gss_ctx_id_t *context_handle,
562                               const gss_cred_id_t acceptor_cred_handle,
563                               const gss_buffer_t input_token_buffer,
564                               const gss_channel_bindings_t input_chan_bindings,
565                               gss_name_t *src_name,
566                               gss_OID *mech_type,
567                               gss_buffer_t output_token,
568                               OM_uint32 *ret_flags,
569                               OM_uint32 *time_rec,
570                               gss_cred_id_t *delegated_cred_handle)
571 {
572         NegTokenInit init_token;
573         OM_uint32 major_status;
574         OM_uint32 minor_status2;
575         gss_buffer_desc ibuf, obuf;
576         gss_buffer_t ot = NULL;
577         gss_OID pref = GSS_KRB5_MECH;
578         unsigned char *buf;
579         size_t buf_size;
580         size_t len, taglen, ni_len;
581         int found = 0;
582         int ret;
583         unsigned i;
584
585         /*
586          * Before doing anything else, see whether this is a SPNEGO
587          * PDU.  If not, dispatch to the GSSAPI library and get out.
588          */
589
590         if (cmp_gss_type(input_token_buffer, GSS_SPNEGO_MECH))
591                 return (gss_accept_sec_context(minor_status,
592                                                context_handle,
593                                                acceptor_cred_handle,
594                                                input_token_buffer,
595                                                input_chan_bindings,
596                                                src_name,
597                                                mech_type,
598                                                output_token,
599                                                ret_flags,
600                                                time_rec,
601                                                delegated_cred_handle));
602
603         /*
604          * If we get here, it's SPNEGO.
605          */
606
607         memset(&init_token, 0, sizeof(init_token));
608
609         ret = gssapi_spnego_decapsulate(minor_status, input_token_buffer,
610                                         &buf, &buf_size, GSS_SPNEGO_MECH);
611         if (ret)
612                 return (ret);
613
614         ret = der_match_tag_and_length(buf, buf_size, ASN1_C_CONTEXT, CONS,
615                                        0, &len, &taglen);
616         if (ret)
617                 return (ret);
618
619         ret = decode_NegTokenInit(buf + taglen, len, &init_token, &ni_len);
620         if (ret) {
621                 *minor_status = EINVAL; /* XXX */
622                 return (GSS_S_DEFECTIVE_TOKEN);
623         }
624
625         for (i = 0; !found && i < init_token.mechTypes.len; ++i) {
626                 unsigned char mechbuf[17];
627                 size_t mech_len;
628
629                 ret = der_put_oid(mechbuf + sizeof(mechbuf) - 1,
630                                   sizeof(mechbuf),
631                                   &init_token.mechTypes.val[i],
632                                   &mech_len);
633                 if (ret)
634                         return (GSS_S_DEFECTIVE_TOKEN);
635                 if (mech_len == GSS_KRB5_MECH->length &&
636                     memcmp(GSS_KRB5_MECH->elements,
637                            mechbuf + sizeof(mechbuf) - mech_len,
638                            mech_len) == 0) {
639                         found = 1;
640                         break;
641                 }
642                 if (mech_len == GSS_MSKRB5_MECH->length &&
643                     memcmp(GSS_MSKRB5_MECH->elements,
644                            mechbuf + sizeof(mechbuf) - mech_len,
645                            mech_len) == 0) {
646                         found = 1;
647                         if (i == 0)
648                                 pref = GSS_MSKRB5_MECH;
649                         break;
650                 }
651         }
652
653         if (!found)
654                 return (send_reject(minor_status, output_token));
655
656         if (i == 0 && init_token.mechToken != NULL) {
657                 ibuf.length = init_token.mechToken->length;
658                 ibuf.value = init_token.mechToken->data;
659
660                 major_status = gss_accept_sec_context(minor_status,
661                                                       context_handle,
662                                                       acceptor_cred_handle,
663                                                       &ibuf,
664                                                       input_chan_bindings,
665                                                       src_name,
666                                                       mech_type,
667                                                       &obuf,
668                                                       ret_flags,
669                                                       time_rec,
670                                                       delegated_cred_handle);
671                 if (GSS_ERROR(major_status)) {
672                         send_reject(&minor_status2, output_token);
673                         return (major_status);
674                 }
675                 ot = &obuf;
676         }
677         ret = send_accept(&minor_status2, output_token, ot, pref);
678         if (ot != NULL && ot->length != 0U)
679                 gss_release_buffer(&minor_status2, ot);
680
681         return (ret);
682 }
683
684 /* decapsulate.c */
685
686 static OM_uint32
687 gssapi_verify_mech_header(u_char ** str,
688                           size_t total_len,
689                           const gss_OID mech)
690 {
691         size_t len, len_len, mech_len, foo;
692         int e;
693         u_char *p = *str;
694
695         if (total_len < 1U)
696                 return (GSS_S_DEFECTIVE_TOKEN);
697         if (*p++ != 0x60)
698                 return (GSS_S_DEFECTIVE_TOKEN);
699         e = der_get_length(p, total_len - 1, &len, &len_len);
700         if (e || 1 + len_len + len != total_len)
701                 return (GSS_S_DEFECTIVE_TOKEN);
702         p += len_len;
703         if (*p++ != 0x06)
704                 return (GSS_S_DEFECTIVE_TOKEN);
705         e = der_get_length(p, total_len - 1 - len_len - 1,
706                            &mech_len, &foo);
707         if (e)
708                 return (GSS_S_DEFECTIVE_TOKEN);
709         p += foo;
710         if (mech_len != mech->length)
711                 return (GSS_S_BAD_MECH);
712         if (memcmp(p, mech->elements, mech->length) != 0)
713                 return (GSS_S_BAD_MECH);
714         p += mech_len;
715         *str = p;
716         return (GSS_S_COMPLETE);
717 }
718
719 /*
720  * Remove the GSS-API wrapping from `in_token' giving `buf and buf_size' Does
721  * not copy data, so just free `in_token'.
722  */
723
724 static OM_uint32
725 gssapi_spnego_decapsulate(OM_uint32 *minor_status,
726                           gss_buffer_t input_token_buffer,
727                           unsigned char **buf,
728                           size_t *buf_len,
729                           const gss_OID mech)
730 {
731         u_char *p;
732         OM_uint32 ret;
733
734         p = input_token_buffer->value;
735         ret = gssapi_verify_mech_header(&p,
736                                         input_token_buffer->length,
737                                         mech);
738         if (ret) {
739                 *minor_status = ret;
740                 return (GSS_S_FAILURE);
741         }
742         *buf_len = input_token_buffer->length -
743                 (p - (u_char *) input_token_buffer->value);
744         *buf = p;
745         return (GSS_S_COMPLETE);
746 }
747
748 /* der_free.c */
749
750 static void
751 free_octet_string(octet_string *k)
752 {
753         free(k->data);
754         k->data = NULL;
755 }
756
757 static void
758 free_oid(oid *k)
759 {
760         free(k->components);
761         k->components = NULL;
762 }
763
764 /* der_get.c */
765
766 /*
767  * All decoding functions take a pointer `p' to first position in which to
768  * read, from the left, `len' which means the maximum number of characters we
769  * are able to read, `ret' were the value will be returned and `size' where
770  * the number of used bytes is stored. Either 0 or an error code is returned.
771  */
772
773 static int
774 der_get_unsigned(const unsigned char *p, size_t len,
775                  unsigned *ret, size_t *size)
776 {
777         unsigned val = 0;
778         size_t oldlen = len;
779
780         while (len--)
781                 val = val * 256 + *p++;
782         *ret = val;
783         if (size)
784                 *size = oldlen;
785         return (0);
786 }
787
788 static int
789 der_get_int(const unsigned char *p, size_t len,
790             int *ret, size_t *size)
791 {
792         int val = 0;
793         size_t oldlen = len;
794
795         if (len > 0U) {
796                 val = (signed char)*p++;
797                 while (--len)
798                         val = val * 256 + *p++;
799         }
800         *ret = val;
801         if (size)
802                 *size = oldlen;
803         return (0);
804 }
805
806 static int
807 der_get_length(const unsigned char *p, size_t len,
808                size_t *val, size_t *size)
809 {
810         size_t v;
811
812         if (len <= 0U)
813                 return (ASN1_OVERRUN);
814         --len;
815         v = *p++;
816         if (v < 128U) {
817                 *val = v;
818                 if (size)
819                         *size = 1;
820         } else {
821                 int e;
822                 size_t l;
823                 unsigned tmp;
824
825                 if (v == 0x80U) {
826                         *val = ASN1_INDEFINITE;
827                         if (size)
828                                 *size = 1;
829                         return (0);
830                 }
831                 v &= 0x7F;
832                 if (len < v)
833                         return (ASN1_OVERRUN);
834                 e = der_get_unsigned(p, v, &tmp, &l);
835                 if (e)
836                         return (e);
837                 *val = tmp;
838                 if (size)
839                         *size = l + 1;
840         }
841         return (0);
842 }
843
844 static int
845 der_get_octet_string(const unsigned char *p, size_t len,
846                      octet_string *data, size_t *size)
847 {
848         data->length = len;
849         data->data = malloc(len);
850         if (data->data == NULL && data->length != 0U)
851                 return (ENOMEM);
852         memcpy(data->data, p, len);
853         if (size)
854                 *size = len;
855         return (0);
856 }
857
858 static int
859 der_get_oid(const unsigned char *p, size_t len,
860             oid *data, size_t *size)
861 {
862         int n;
863         size_t oldlen = len;
864
865         if (len < 1U)
866                 return (ASN1_OVERRUN);
867
868         data->components = malloc(len * sizeof(*data->components));
869         if (data->components == NULL && len != 0U)
870                 return (ENOMEM);
871         data->components[0] = (*p) / 40;
872         data->components[1] = (*p) % 40;
873         --len;
874         ++p;
875         for (n = 2; len > 0U; ++n) {
876                 unsigned u = 0;
877
878                 do {
879                         --len;
880                         u = u * 128 + (*p++ % 128);
881                 } while (len > 0U && p[-1] & 0x80);
882                 data->components[n] = u;
883         }
884         if (p[-1] & 0x80) {
885                 free_oid(data);
886                 return (ASN1_OVERRUN);
887         }
888         data->length = n;
889         if (size)
890                 *size = oldlen;
891         return (0);
892 }
893
894 static int
895 der_get_tag(const unsigned char *p, size_t len,
896             Der_class *class, Der_type *type,
897             int *tag, size_t *size)
898 {
899         if (len < 1U)
900                 return (ASN1_OVERRUN);
901         *class = (Der_class) (((*p) >> 6) & 0x03);
902         *type = (Der_type) (((*p) >> 5) & 0x01);
903         *tag = (*p) & 0x1F;
904         if (size)
905                 *size = 1;
906         return (0);
907 }
908
909 static int
910 der_match_tag(const unsigned char *p, size_t len,
911               Der_class class, Der_type type,
912               int tag, size_t *size)
913 {
914         size_t l;
915         Der_class thisclass;
916         Der_type thistype;
917         int thistag;
918         int e;
919
920         e = der_get_tag(p, len, &thisclass, &thistype, &thistag, &l);
921         if (e)
922                 return (e);
923         if (class != thisclass || type != thistype)
924                 return (ASN1_BAD_ID);
925         if (tag > thistag)
926                 return (ASN1_MISPLACED_FIELD);
927         if (tag < thistag)
928                 return (ASN1_MISSING_FIELD);
929         if (size)
930                 *size = l;
931         return (0);
932 }
933
934 static int
935 der_match_tag_and_length(const unsigned char *p, size_t len,
936                          Der_class class, Der_type type, int tag,
937                          size_t *length_ret, size_t *size)
938 {
939         size_t l, ret = 0;
940         int e;
941
942         e = der_match_tag(p, len, class, type, tag, &l);
943         if (e)
944                 return (e);
945         p += l;
946         len -= l;
947         ret += l;
948         e = der_get_length(p, len, length_ret, &l);
949         if (e)
950                 return (e);
951         p += l;
952         len -= l;
953         ret += l;
954         if (size)
955                 *size = ret;
956         return (0);
957 }
958
959 static int
960 decode_enumerated(const unsigned char *p, size_t len, void *num, size_t *size)
961 {
962         size_t ret = 0;
963         size_t l, reallen;
964         int e;
965
966         e = der_match_tag(p, len, ASN1_C_UNIV, PRIM, UT_Enumerated, &l);
967         if (e)
968                 return (e);
969         p += l;
970         len -= l;
971         ret += l;
972         e = der_get_length(p, len, &reallen, &l);
973         if (e)
974                 return (e);
975         p += l;
976         len -= l;
977         ret += l;
978         e = der_get_int(p, reallen, num, &l);
979         if (e)
980                 return (e);
981         p += l;
982         len -= l;
983         ret += l;
984         if (size)
985                 *size = ret;
986         return (0);
987 }
988
989 static int
990 decode_octet_string(const unsigned char *p, size_t len,
991                     octet_string *k, size_t *size)
992 {
993         size_t ret = 0;
994         size_t l;
995         int e;
996         size_t slen;
997
998         e = der_match_tag(p, len, ASN1_C_UNIV, PRIM, UT_OctetString, &l);
999         if (e)
1000                 return (e);
1001         p += l;
1002         len -= l;
1003         ret += l;
1004
1005         e = der_get_length(p, len, &slen, &l);
1006         if (e)
1007                 return (e);
1008         p += l;
1009         len -= l;
1010         ret += l;
1011         if (len < slen)
1012                 return (ASN1_OVERRUN);
1013
1014         e = der_get_octet_string(p, slen, k, &l);
1015         if (e)
1016                 return (e);
1017         p += l;
1018         len -= l;
1019         ret += l;
1020         if (size)
1021                 *size = ret;
1022         return (0);
1023 }
1024
1025 static int
1026 decode_oid(const unsigned char *p, size_t len,
1027            oid *k, size_t *size)
1028 {
1029         size_t ret = 0;
1030         size_t l;
1031         int e;
1032         size_t slen;
1033
1034         e = der_match_tag(p, len, ASN1_C_UNIV, PRIM, UT_OID, &l);
1035         if (e)
1036                 return (e);
1037         p += l;
1038         len -= l;
1039         ret += l;
1040
1041         e = der_get_length(p, len, &slen, &l);
1042         if (e)
1043                 return (e);
1044         p += l;
1045         len -= l;
1046         ret += l;
1047         if (len < slen)
1048                 return (ASN1_OVERRUN);
1049
1050         e = der_get_oid(p, slen, k, &l);
1051         if (e)
1052                 return (e);
1053         p += l;
1054         len -= l;
1055         ret += l;
1056         if (size)
1057                 *size = ret;
1058         return (0);
1059 }
1060
1061 static int
1062 fix_dce(size_t reallen, size_t *len)
1063 {
1064         if (reallen == ASN1_INDEFINITE)
1065                 return (1);
1066         if (*len < reallen)
1067                 return (-1);
1068         *len = reallen;
1069         return (0);
1070 }
1071
1072 /* der_length.c */
1073
1074 static size_t
1075 len_unsigned(unsigned val)
1076 {
1077         size_t ret = 0;
1078
1079         do {
1080                 ++ret;
1081                 val /= 256;
1082         } while (val);
1083         return (ret);
1084 }
1085
1086 static size_t
1087 length_len(size_t len)
1088 {
1089         if (len < 128U)
1090                 return (1);
1091         else
1092                 return (len_unsigned(len) + 1);
1093 }
1094
1095
1096 /* der_put.c */
1097
1098 /*
1099  * All encoding functions take a pointer `p' to first position in which to
1100  * write, from the right, `len' which means the maximum number of characters
1101  * we are able to write.  The function returns the number of characters
1102  * written in `size' (if non-NULL). The return value is 0 or an error.
1103  */
1104
1105 static int
1106 der_put_unsigned(unsigned char *p, size_t len, unsigned val, size_t *size)
1107 {
1108         unsigned char *base = p;
1109
1110         if (val) {
1111                 while (len > 0U && val) {
1112                         *p-- = val % 256;
1113                         val /= 256;
1114                         --len;
1115                 }
1116                 if (val != 0)
1117                         return (ASN1_OVERFLOW);
1118                 else {
1119                         *size = base - p;
1120                         return (0);
1121                 }
1122         } else if (len < 1U)
1123                 return (ASN1_OVERFLOW);
1124         else {
1125                 *p = 0;
1126                 *size = 1;
1127                 return (0);
1128         }
1129 }
1130
1131 static int
1132 der_put_int(unsigned char *p, size_t len, int val, size_t *size)
1133 {
1134         unsigned char *base = p;
1135
1136         if (val >= 0) {
1137                 do {
1138                         if (len < 1U)
1139                                 return (ASN1_OVERFLOW);
1140                         *p-- = val % 256;
1141                         len--;
1142                         val /= 256;
1143                 } while (val);
1144                 if (p[1] >= 128) {
1145                         if (len < 1U)
1146                                 return (ASN1_OVERFLOW);
1147                         *p-- = 0;
1148                         len--;
1149                 }
1150         } else {
1151                 val = ~val;
1152                 do {
1153                         if (len < 1U)
1154                                 return (ASN1_OVERFLOW);
1155                         *p-- = ~(val % 256);
1156                         len--;
1157                         val /= 256;
1158                 } while (val);
1159                 if (p[1] < 128) {
1160                         if (len < 1U)
1161                                 return (ASN1_OVERFLOW);
1162                         *p-- = 0xff;
1163                         len--;
1164                 }
1165         }
1166         *size = base - p;
1167         return (0);
1168 }
1169
1170 static int
1171 der_put_length(unsigned char *p, size_t len, size_t val, size_t *size)
1172 {
1173         if (len < 1U)
1174                 return (ASN1_OVERFLOW);
1175         if (val < 128U) {
1176                 *p = val;
1177                 *size = 1;
1178                 return (0);
1179         } else {
1180                 size_t l;
1181                 int e;
1182
1183                 e = der_put_unsigned(p, len - 1, val, &l);
1184                 if (e)
1185                         return (e);
1186                 p -= l;
1187                 *p = 0x80 | l;
1188                 *size = l + 1;
1189                 return (0);
1190         }
1191 }
1192
1193 static int
1194 der_put_octet_string(unsigned char *p, size_t len,
1195                      const octet_string *data, size_t *size)
1196 {
1197         if (len < data->length)
1198                 return (ASN1_OVERFLOW);
1199         p -= data->length;
1200         len -= data->length;
1201         memcpy(p + 1, data->data, data->length);
1202         *size = data->length;
1203         return (0);
1204 }
1205
1206 static int
1207 der_put_oid(unsigned char *p, size_t len,
1208             const oid *data, size_t *size)
1209 {
1210         unsigned char *base = p;
1211         int n;
1212
1213         for (n = data->length - 1; n >= 2; --n) {
1214                 unsigned        u = data->components[n];
1215
1216                 if (len < 1U)
1217                         return (ASN1_OVERFLOW);
1218                 *p-- = u % 128;
1219                 u /= 128;
1220                 --len;
1221                 while (u > 0) {
1222                         if (len < 1U)
1223                                 return (ASN1_OVERFLOW);
1224                         *p-- = 128 + u % 128;
1225                         u /= 128;
1226                         --len;
1227                 }
1228         }
1229         if (len < 1U)
1230                 return (ASN1_OVERFLOW);
1231         *p-- = 40 * data->components[0] + data->components[1];
1232         *size = base - p;
1233         return (0);
1234 }
1235
1236 static int
1237 der_put_tag(unsigned char *p, size_t len, Der_class class, Der_type type,
1238             int tag, size_t *size)
1239 {
1240         if (len < 1U)
1241                 return (ASN1_OVERFLOW);
1242         *p = (class << 6) | (type << 5) | tag;  /* XXX */
1243         *size = 1;
1244         return (0);
1245 }
1246
1247 static int
1248 der_put_length_and_tag(unsigned char *p, size_t len, size_t len_val,
1249                        Der_class class, Der_type type, int tag, size_t *size)
1250 {
1251         size_t ret = 0;
1252         size_t l;
1253         int e;
1254
1255         e = der_put_length(p, len, len_val, &l);
1256         if (e)
1257                 return (e);
1258         p -= l;
1259         len -= l;
1260         ret += l;
1261         e = der_put_tag(p, len, class, type, tag, &l);
1262         if (e)
1263                 return (e);
1264         p -= l;
1265         len -= l;
1266         ret += l;
1267         *size = ret;
1268         return (0);
1269 }
1270
1271 static int
1272 encode_enumerated(unsigned char *p, size_t len, const void *data, size_t *size)
1273 {
1274         unsigned num = *(const unsigned *)data;
1275         size_t ret = 0;
1276         size_t l;
1277         int e;
1278
1279         e = der_put_int(p, len, num, &l);
1280         if (e)
1281                 return (e);
1282         p -= l;
1283         len -= l;
1284         ret += l;
1285         e = der_put_length_and_tag(p, len, l, ASN1_C_UNIV, PRIM, UT_Enumerated, &l);
1286         if (e)
1287                 return (e);
1288         p -= l;
1289         len -= l;
1290         ret += l;
1291         *size = ret;
1292         return (0);
1293 }
1294
1295 static int
1296 encode_octet_string(unsigned char *p, size_t len,
1297                     const octet_string *k, size_t *size)
1298 {
1299         size_t ret = 0;
1300         size_t l;
1301         int e;
1302
1303         e = der_put_octet_string(p, len, k, &l);
1304         if (e)
1305                 return (e);
1306         p -= l;
1307         len -= l;
1308         ret += l;
1309         e = der_put_length_and_tag(p, len, l, ASN1_C_UNIV, PRIM, UT_OctetString, &l);
1310         if (e)
1311                 return (e);
1312         p -= l;
1313         len -= l;
1314         ret += l;
1315         *size = ret;
1316         return (0);
1317 }
1318
1319 static int
1320 encode_oid(unsigned char *p, size_t len,
1321            const oid *k, size_t *size)
1322 {
1323         size_t ret = 0;
1324         size_t l;
1325         int e;
1326
1327         e = der_put_oid(p, len, k, &l);
1328         if (e)
1329                 return (e);
1330         p -= l;
1331         len -= l;
1332         ret += l;
1333         e = der_put_length_and_tag(p, len, l, ASN1_C_UNIV, PRIM, UT_OID, &l);
1334         if (e)
1335                 return (e);
1336         p -= l;
1337         len -= l;
1338         ret += l;
1339         *size = ret;
1340         return (0);
1341 }
1342
1343
1344 /* encapsulate.c */
1345
1346 static void
1347 gssapi_encap_length(size_t data_len,
1348                     size_t *len,
1349                     size_t *total_len,
1350                     const gss_OID mech)
1351 {
1352         size_t len_len;
1353
1354         *len = 1 + 1 + mech->length + data_len;
1355
1356         len_len = length_len(*len);
1357
1358         *total_len = 1 + len_len + *len;
1359 }
1360
1361 static u_char *
1362 gssapi_mech_make_header(u_char *p,
1363                         size_t len,
1364                         const gss_OID mech)
1365 {
1366         int e;
1367         size_t len_len, foo;
1368
1369         *p++ = 0x60;
1370         len_len = length_len(len);
1371         e = der_put_length(p + len_len - 1, len_len, len, &foo);
1372         if (e || foo != len_len)
1373                 return (NULL);
1374         p += len_len;
1375         *p++ = 0x06;
1376         *p++ = mech->length;
1377         memcpy(p, mech->elements, mech->length);
1378         p += mech->length;
1379         return (p);
1380 }
1381
1382 /*
1383  * Give it a krb5_data and it will encapsulate with extra GSS-API wrappings.
1384  */
1385
1386 static OM_uint32
1387 gssapi_spnego_encapsulate(OM_uint32 * minor_status,
1388                           unsigned char *buf,
1389                           size_t buf_size,
1390                           gss_buffer_t output_token,
1391                           const gss_OID mech)
1392 {
1393         size_t len, outer_len;
1394         u_char *p;
1395
1396         gssapi_encap_length(buf_size, &len, &outer_len, mech);
1397
1398         output_token->length = outer_len;
1399         output_token->value = malloc(outer_len);
1400         if (output_token->value == NULL) {
1401                 *minor_status = ENOMEM;
1402                 return (GSS_S_FAILURE);
1403         }
1404         p = gssapi_mech_make_header(output_token->value, len, mech);
1405         if (p == NULL) {
1406                 if (output_token->length != 0U)
1407                         gss_release_buffer(minor_status, output_token);
1408                 return (GSS_S_FAILURE);
1409         }
1410         memcpy(p, buf, buf_size);
1411         return (GSS_S_COMPLETE);
1412 }
1413
1414 /* init_sec_context.c */
1415 /*
1416  * SPNEGO wrapper for Kerberos5 GSS-API kouril@ics.muni.cz, 2003 (mostly
1417  * based on Heimdal code)
1418  */
1419
1420 static int
1421 add_mech(MechTypeList * mech_list, gss_OID mech)
1422 {
1423         MechType *tmp;
1424         int ret;
1425
1426         tmp = realloc(mech_list->val, (mech_list->len + 1) * sizeof(*tmp));
1427         if (tmp == NULL)
1428                 return (ENOMEM);
1429         mech_list->val = tmp;
1430
1431         ret = der_get_oid(mech->elements, mech->length,
1432                           &mech_list->val[mech_list->len], NULL);
1433         if (ret)
1434                 return (ret);
1435
1436         mech_list->len++;
1437         return (0);
1438 }
1439
1440 /*
1441  * return the length of the mechanism in token or -1
1442  * (which implies that the token was bad - GSS_S_DEFECTIVE_TOKEN
1443  */
1444
1445 static ssize_t
1446 gssapi_krb5_get_mech(const u_char *ptr,
1447                      size_t total_len,
1448                      const u_char **mech_ret)
1449 {
1450         size_t len, len_len, mech_len, foo;
1451         const u_char *p = ptr;
1452         int e;
1453
1454         if (total_len < 1U)
1455                 return (-1);
1456         if (*p++ != 0x60)
1457                 return (-1);
1458         e = der_get_length (p, total_len - 1, &len, &len_len);
1459         if (e || 1 + len_len + len != total_len)
1460                 return (-1);
1461         p += len_len;
1462         if (*p++ != 0x06)
1463                 return (-1);
1464         e = der_get_length (p, total_len - 1 - len_len - 1,
1465                             &mech_len, &foo);
1466         if (e)
1467                 return (-1);
1468         p += foo;
1469         *mech_ret = p;
1470         return (mech_len);
1471 }
1472
1473 static OM_uint32
1474 spnego_initial(OM_uint32 *minor_status,
1475                const gss_cred_id_t initiator_cred_handle,
1476                gss_ctx_id_t *context_handle,
1477                const gss_name_t target_name,
1478                const gss_OID mech_type,
1479                OM_uint32 req_flags,
1480                OM_uint32 time_req,
1481                const gss_channel_bindings_t input_chan_bindings,
1482                const gss_buffer_t input_token,
1483                gss_OID *actual_mech_type,
1484                gss_buffer_t output_token,
1485                OM_uint32 *ret_flags,
1486                OM_uint32 *time_rec)
1487 {
1488         NegTokenInit token_init;
1489         OM_uint32 major_status, minor_status2;
1490         gss_buffer_desc krb5_output_token = GSS_C_EMPTY_BUFFER;
1491         unsigned char *buf = NULL;
1492         size_t buf_size;
1493         size_t len;
1494         int ret;
1495
1496         (void)mech_type;
1497
1498         memset(&token_init, 0, sizeof(token_init));
1499
1500         ret = add_mech(&token_init.mechTypes, GSS_KRB5_MECH);
1501         if (ret) {
1502                 *minor_status = ret;
1503                 ret = GSS_S_FAILURE;
1504                 goto end;
1505         }
1506
1507         major_status = gss_init_sec_context(minor_status,
1508                                             initiator_cred_handle,
1509                                             context_handle,
1510                                             target_name,
1511                                             GSS_KRB5_MECH,
1512                                             req_flags,
1513                                             time_req,
1514                                             input_chan_bindings,
1515                                             input_token,
1516                                             actual_mech_type,
1517                                             &krb5_output_token,
1518                                             ret_flags,
1519                                             time_rec);
1520         if (GSS_ERROR(major_status)) {
1521                 ret = major_status;
1522                 goto end;
1523         }
1524         if (krb5_output_token.length > 0U) {
1525                 token_init.mechToken = malloc(sizeof(*token_init.mechToken));
1526                 if (token_init.mechToken == NULL) {
1527                         *minor_status = ENOMEM;
1528                         ret = GSS_S_FAILURE;
1529                         goto end;
1530                 }
1531                 token_init.mechToken->data = krb5_output_token.value;
1532                 token_init.mechToken->length = krb5_output_token.length;
1533         }
1534         /*
1535          * The MS implementation of SPNEGO seems to not like the mechListMIC
1536          * field, so we omit it (it's optional anyway)
1537          */
1538
1539         buf_size = 1024;
1540         buf = malloc(buf_size);
1541
1542         do {
1543                 ret = encode_NegTokenInit(buf + buf_size - 1,
1544                                           buf_size,
1545                                           &token_init, &len);
1546                 if (ret == 0) {
1547                         size_t tmp;
1548
1549                         ret = der_put_length_and_tag(buf + buf_size - len - 1,
1550                                                      buf_size - len,
1551                                                      len,
1552                                                      ASN1_C_CONTEXT,
1553                                                      CONS,
1554                                                      0,
1555                                                      &tmp);
1556                         if (ret == 0)
1557                                 len += tmp;
1558                 }
1559                 if (ret) {
1560                         if (ret == ASN1_OVERFLOW) {
1561                                 u_char *tmp;
1562
1563                                 buf_size *= 2;
1564                                 tmp = realloc(buf, buf_size);
1565                                 if (tmp == NULL) {
1566                                         *minor_status = ENOMEM;
1567                                         ret = GSS_S_FAILURE;
1568                                         goto end;
1569                                 }
1570                                 buf = tmp;
1571                         } else {
1572                                 *minor_status = ret;
1573                                 ret = GSS_S_FAILURE;
1574                                 goto end;
1575                         }
1576                 }
1577         } while (ret == ASN1_OVERFLOW);
1578
1579         ret = gssapi_spnego_encapsulate(minor_status,
1580                                         buf + buf_size - len, len,
1581                                         output_token, GSS_SPNEGO_MECH);
1582         if (ret == GSS_S_COMPLETE)
1583                 ret = major_status;
1584
1585 end:
1586         if (token_init.mechToken != NULL) {
1587                 free(token_init.mechToken);
1588                 token_init.mechToken = NULL;
1589         }
1590         free_NegTokenInit(&token_init);
1591         if (krb5_output_token.length != 0U)
1592                 gss_release_buffer(&minor_status2, &krb5_output_token);
1593         if (buf)
1594                 free(buf);
1595
1596         return (ret);
1597 }
1598
1599 static OM_uint32
1600 spnego_reply(OM_uint32 *minor_status,
1601              const gss_cred_id_t initiator_cred_handle,
1602              gss_ctx_id_t *context_handle,
1603              const gss_name_t target_name,
1604              const gss_OID mech_type,
1605              OM_uint32 req_flags,
1606              OM_uint32 time_req,
1607              const gss_channel_bindings_t input_chan_bindings,
1608              const gss_buffer_t input_token,
1609              gss_OID *actual_mech_type,
1610              gss_buffer_t output_token,
1611              OM_uint32 *ret_flags,
1612              OM_uint32 *time_rec)
1613 {
1614         OM_uint32 ret;
1615         NegTokenResp resp;
1616         unsigned char *buf;
1617         size_t buf_size;
1618         u_char oidbuf[17];
1619         size_t oidlen;
1620         gss_buffer_desc sub_token;
1621         ssize_t mech_len;
1622         const u_char *p;
1623         size_t len, taglen;
1624
1625         (void)mech_type;
1626
1627         output_token->length = 0;
1628         output_token->value  = NULL;
1629
1630         /*
1631          * SPNEGO doesn't include gss wrapping on SubsequentContextToken
1632          * like the Kerberos 5 mech does. But lets check for it anyway.
1633          */
1634
1635         mech_len = gssapi_krb5_get_mech(input_token->value,
1636                                         input_token->length,
1637                                         &p);
1638
1639         if (mech_len < 0) {
1640                 buf = input_token->value;
1641                 buf_size = input_token->length;
1642         } else if ((size_t)mech_len == GSS_KRB5_MECH->length &&
1643                    memcmp(GSS_KRB5_MECH->elements, p, mech_len) == 0)
1644                 return (gss_init_sec_context(minor_status,
1645                                              initiator_cred_handle,
1646                                              context_handle,
1647                                              target_name,
1648                                              GSS_KRB5_MECH,
1649                                              req_flags,
1650                                              time_req,
1651                                              input_chan_bindings,
1652                                              input_token,
1653                                              actual_mech_type,
1654                                              output_token,
1655                                              ret_flags,
1656                                              time_rec));
1657         else if ((size_t)mech_len == GSS_SPNEGO_MECH->length &&
1658                  memcmp(GSS_SPNEGO_MECH->elements, p, mech_len) == 0) {
1659                 ret = gssapi_spnego_decapsulate(minor_status,
1660                                                 input_token,
1661                                                 &buf,
1662                                                 &buf_size,
1663                                                 GSS_SPNEGO_MECH);
1664                 if (ret)
1665                         return (ret);
1666         } else
1667                 return (GSS_S_BAD_MECH);
1668
1669         ret = der_match_tag_and_length(buf, buf_size,
1670                                        ASN1_C_CONTEXT, CONS, 1, &len, &taglen);
1671         if (ret)
1672                 return (ret);
1673
1674         if(len > buf_size - taglen)
1675                 return (ASN1_OVERRUN);
1676
1677         ret = decode_NegTokenResp(buf + taglen, len, &resp, NULL);
1678         if (ret) {
1679                 *minor_status = ENOMEM;
1680                 return (GSS_S_FAILURE);
1681         }
1682
1683         if (resp.negState == NULL ||
1684             *(resp.negState) == reject ||
1685             resp.supportedMech == NULL) {
1686                 free_NegTokenResp(&resp);
1687                 return (GSS_S_BAD_MECH);
1688         }
1689
1690         ret = der_put_oid(oidbuf + sizeof(oidbuf) - 1,
1691                           sizeof(oidbuf),
1692                           resp.supportedMech,
1693                           &oidlen);
1694         if (ret || oidlen != GSS_KRB5_MECH->length ||
1695             memcmp(oidbuf + sizeof(oidbuf) - oidlen,
1696                    GSS_KRB5_MECH->elements,
1697                    oidlen) != 0) {
1698                 free_NegTokenResp(&resp);
1699                 return GSS_S_BAD_MECH;
1700         }
1701
1702         if (resp.responseToken != NULL) {
1703                 sub_token.length = resp.responseToken->length;
1704                 sub_token.value  = resp.responseToken->data;
1705         } else {
1706                 sub_token.length = 0;
1707                 sub_token.value  = NULL;
1708         }
1709
1710         ret = gss_init_sec_context(minor_status,
1711                                    initiator_cred_handle,
1712                                    context_handle,
1713                                    target_name,
1714                                    GSS_KRB5_MECH,
1715                                    req_flags,
1716                                    time_req,
1717                                    input_chan_bindings,
1718                                    &sub_token,
1719                                    actual_mech_type,
1720                                    output_token,
1721                                    ret_flags,
1722                                    time_rec);
1723         if (ret) {
1724                 free_NegTokenResp(&resp);
1725                 return (ret);
1726         }
1727
1728         /*
1729          * XXXSRA I don't think this limited implementation ever needs
1730          * to check the MIC -- our preferred mechanism (Kerberos)
1731          * authenticates its own messages and is the only mechanism
1732          * we'll accept, so if the mechanism negotiation completes
1733          * successfully, we don't need the MIC.  See RFC 4178.
1734          */
1735
1736         free_NegTokenResp(&resp);
1737         return (ret);
1738 }
1739
1740
1741
1742 OM_uint32
1743 gss_init_sec_context_spnego(OM_uint32 *minor_status,
1744                             const gss_cred_id_t initiator_cred_handle,
1745                             gss_ctx_id_t *context_handle,
1746                             const gss_name_t target_name,
1747                             const gss_OID mech_type,
1748                             OM_uint32 req_flags,
1749                             OM_uint32 time_req,
1750                             const gss_channel_bindings_t input_chan_bindings,
1751                             const gss_buffer_t input_token,
1752                             gss_OID *actual_mech_type,
1753                             gss_buffer_t output_token,
1754                             OM_uint32 *ret_flags,
1755                             OM_uint32 *time_rec)
1756 {
1757         /* Dirty trick to suppress compiler warnings */
1758
1759         /* Figure out whether we're starting over or processing a reply */
1760
1761         if (input_token == GSS_C_NO_BUFFER || input_token->length == 0U)
1762                 return (spnego_initial(minor_status,
1763                                        initiator_cred_handle,
1764                                        context_handle,
1765                                        target_name,
1766                                        mech_type,
1767                                        req_flags,
1768                                        time_req,
1769                                        input_chan_bindings,
1770                                        input_token,
1771                                        actual_mech_type,
1772                                        output_token,
1773                                        ret_flags,
1774                                        time_rec));
1775         else
1776                 return (spnego_reply(minor_status,
1777                                      initiator_cred_handle,
1778                                      context_handle,
1779                                      target_name,
1780                                      mech_type,
1781                                      req_flags,
1782                                      time_req,
1783                                      input_chan_bindings,
1784                                      input_token,
1785                                      actual_mech_type,
1786                                      output_token,
1787                                      ret_flags,
1788                                      time_rec));
1789 }
1790
1791 #endif /* GSSAPI */