Fixes for Heimdal (macOS) builds from Stefan.
[mech_eap.git] / mech_eap / util_token.c
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 1993 by OpenVision Technologies, Inc.
34  *
35  * Permission to use, copy, modify, distribute, and sell this software
36  * and its documentation for any purpose is hereby granted without fee,
37  * provided that the above copyright notice appears in all copies and
38  * that both that copyright notice and this permission notice appear in
39  * supporting documentation, and that the name of OpenVision not be used
40  * in advertising or publicity pertaining to distribution of the software
41  * without specific, written prior permission. OpenVision makes no
42  * representations about the suitability of this software for any
43  * purpose.  It is provided "as is" without express or implied warranty.
44  *
45  * OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
46  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
47  * EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
48  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
49  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
50  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
51  * PERFORMANCE OF THIS SOFTWARE.
52  */
53
54 /*
55  * Utility routines for GSS tokens.
56  */
57
58 #include "gssapiP_eap.h"
59
60 OM_uint32
61 gssEapEncodeInnerTokens(OM_uint32 *minor,
62                         struct gss_eap_token_buffer_set *tokens,
63                         gss_buffer_t buffer)
64 {
65     OM_uint32 major, tmpMinor;
66     size_t required = 0, i;
67     unsigned char *p;
68
69     buffer->value = NULL;
70     buffer->length = 0;
71
72     for (i = 0; i < tokens->buffers.count; i++) {
73         required += 8 + tokens->buffers.elements[i].length;
74     }
75
76     /*
77      * We must always return a non-NULL token otherwise the calling state
78      * machine assumes we are finished. Hence care in case malloc(0) does
79      * return NULL.
80      */
81     buffer->value = GSSEAP_MALLOC(required ? required : 1);
82     if (buffer->value == NULL) {
83         major = GSS_S_FAILURE;
84         *minor = ENOMEM;
85         goto cleanup;
86     }
87
88     buffer->length = required;
89     p = (unsigned char *)buffer->value;
90
91     for (i = 0; i < tokens->buffers.count; i++) {
92         gss_buffer_t tokenBuffer = &tokens->buffers.elements[i];
93
94         GSSEAP_ASSERT((tokens->types[i] & ITOK_FLAG_VERIFIED) == 0); /* private flag */
95
96          /*
97           * Extensions are encoded as type-length-value, where the upper
98           * bit of the type indicates criticality.
99           */
100         store_uint32_be(tokens->types[i], &p[0]);
101         store_uint32_be(tokenBuffer->length, &p[4]);
102         memcpy(&p[8], tokenBuffer->value, tokenBuffer->length);
103
104         p += 8 + tokenBuffer->length;
105     }
106
107     GSSEAP_ASSERT(p == (unsigned char *)buffer->value + required);
108     GSSEAP_ASSERT(buffer->value != NULL);
109
110     major = GSS_S_COMPLETE;
111     *minor = 0;
112
113 cleanup:
114     if (GSS_ERROR(major)) {
115         gss_release_buffer(&tmpMinor, buffer);
116     }
117
118     return major;
119 }
120
121 OM_uint32
122 gssEapDecodeInnerTokens(OM_uint32 *minor,
123                         const gss_buffer_t buffer,
124                         struct gss_eap_token_buffer_set *tokens)
125 {
126     OM_uint32 major, tmpMinor;
127     unsigned char *p;
128     size_t count = 0;
129     size_t remain;
130
131     tokens->buffers.count = 0;
132     tokens->buffers.elements = NULL;
133     tokens->types = NULL;
134
135     if (buffer->length == 0) {
136         major = GSS_S_COMPLETE;
137         goto cleanup;
138     }
139
140     p = (unsigned char *)buffer->value;
141     remain = buffer->length;
142
143     do {
144         OM_uint32 *ntypes;
145         gss_buffer_desc tokenBuffer, *newTokenBuffers;
146
147         if (remain < 8) {
148             major = GSS_S_DEFECTIVE_TOKEN;
149             *minor = GSSEAP_TOK_TRUNC;
150             goto cleanup;
151         }
152
153         if (tokens->buffers.count <= count) {
154             if (count == 0)
155                 count = 1;
156             else
157                 count *= 2;
158
159             ntypes = GSSEAP_MALLOC(count * sizeof(OM_uint32));
160             if (ntypes == NULL) {
161                 major = GSS_S_FAILURE;
162                 *minor = ENOMEM;
163                 goto cleanup;
164             }
165             if (tokens->types != NULL) {
166                 memcpy(ntypes, tokens->types, tokens->buffers.count * sizeof(OM_uint32));
167                 GSSEAP_FREE(tokens->types);
168             }
169             tokens->types = ntypes;
170
171             newTokenBuffers = GSSEAP_MALLOC(count * sizeof(gss_buffer_desc));
172             if (newTokenBuffers == NULL) {
173                 major = GSS_S_FAILURE;
174                 *minor = ENOMEM;
175                 goto cleanup;
176             }
177             if (tokens->buffers.elements != NULL) {
178                 memcpy(newTokenBuffers, tokens->buffers.elements,
179                        tokens->buffers.count * sizeof(gss_buffer_desc));
180                 GSSEAP_FREE(tokens->buffers.elements);
181             }
182             tokens->buffers.elements = newTokenBuffers;
183         }
184
185         tokens->types[tokens->buffers.count] = load_uint32_be(&p[0]);
186         tokenBuffer.length = load_uint32_be(&p[4]);
187
188         if (remain < 8 + tokenBuffer.length) {
189             major = GSS_S_DEFECTIVE_TOKEN;
190             *minor = GSSEAP_TOK_TRUNC;
191             goto cleanup;
192         }
193         tokenBuffer.value = &p[8];
194
195         tokens->buffers.elements[tokens->buffers.count] = tokenBuffer;
196         tokens->buffers.count++;
197
198         p      += 8 + tokenBuffer.length;
199         remain -= 8 + tokenBuffer.length;
200     } while (remain != 0);
201
202     major = GSS_S_COMPLETE;
203     *minor = 0;
204
205 cleanup:
206     if (GSS_ERROR(major))
207         gssEapReleaseInnerTokens(&tmpMinor, tokens, 0);
208
209     return major;
210 }
211
212 /*
213  * $Id: util_token.c 23457 2009-12-08 00:04:48Z tlyu $
214  */
215
216 /* XXXX this code currently makes the assumption that a mech oid will
217    never be longer than 127 bytes.  This assumption is not inherent in
218    the interfaces, so the code can be fixed if the OSI namespace
219    balloons unexpectedly. */
220
221 /*
222  * Each token looks like this:
223  * 0x60                 tag for APPLICATION 0, SEQUENCE
224  *                              (constructed, definite-length)
225  * <length>             possible multiple bytes, need to parse/generate
226  * 0x06                 tag for OBJECT IDENTIFIER
227  * <moid_length>        compile-time constant string (assume 1 byte)
228  * <moid_bytes>         compile-time constant string
229  * <inner_bytes>        the ANY containing the application token
230  * bytes 0,1 are the token type
231  * bytes 2,n are the token data
232  *
233  * Note that the token type field is a feature of RFC 1964 mechanisms and
234  * is not used by other GSSAPI mechanisms.  As such, a token type of -1
235  * is interpreted to mean that no token type should be expected or
236  * generated.
237  *
238  * For the purposes of this abstraction, the token "header" consists of
239  * the sequence tag and length octets, the mech OID DER encoding, and the
240  * first two inner bytes, which indicate the token type.  The token
241  * "body" consists of everything else.
242  */
243
244 static size_t
245 der_length_size(size_t length)
246 {
247     if (length < (1<<7))
248         return 1;
249     else if (length < (1<<8))
250         return 2;
251 #if INT_MAX == 0x7fff
252     else
253         return 3;
254 #else
255     else if (length < (1<<16))
256         return 3;
257     else if (length < (1<<24))
258         return 4;
259     else
260         return 5;
261 #endif
262 }
263
264 static void
265 der_write_length(unsigned char **buf, size_t length)
266 {
267     if (length < (1<<7)) {
268         *(*buf)++ = (unsigned char)length;
269     } else {
270         *(*buf)++ = (unsigned char)(der_length_size(length)+127);
271 #if INT_MAX > 0x7fff
272         if (length >= (1<<24))
273             *(*buf)++ = (unsigned char)(length>>24);
274         if (length >= (1<<16))
275             *(*buf)++ = (unsigned char)((length>>16)&0xff);
276 #endif
277         if (length >= (1<<8))
278             *(*buf)++ = (unsigned char)((length>>8)&0xff);
279         *(*buf)++ = (unsigned char)(length&0xff);
280     }
281 }
282
283 /* returns decoded length, or < 0 on failure.  Advances buf and
284    decrements bufsize */
285
286 static int
287 der_read_length(unsigned char **buf, ssize_t *bufsize)
288 {
289     unsigned char sf;
290     int ret;
291
292     if (*bufsize < 1)
293         return -1;
294
295     sf = *(*buf)++;
296     (*bufsize)--;
297     if (sf & 0x80) {
298         if ((sf &= 0x7f) > ((*bufsize)-1))
299             return -1;
300         if (sf > sizeof(int))
301             return -1;
302         ret = 0;
303         for (; sf; sf--) {
304             ret = (ret<<8) + (*(*buf)++);
305             (*bufsize)--;
306         }
307     } else {
308         ret = sf;
309     }
310
311     return ret;
312 }
313
314 /* returns the length of a token, given the mech oid and the body size */
315
316 size_t
317 tokenSize(const gss_OID_desc *mech, size_t body_size)
318 {
319     GSSEAP_ASSERT(mech != GSS_C_NO_OID);
320
321     /* set body_size to sequence contents size */
322     body_size += 4 + (size_t) mech->length;         /* NEED overflow check */
323     return 1 + der_length_size(body_size) + body_size;
324 }
325
326 /* fills in a buffer with the token header.  The buffer is assumed to
327    be the right size.  buf is advanced past the token header */
328
329 void
330 makeTokenHeader(
331     const gss_OID_desc *mech,
332     size_t body_size,
333     unsigned char **buf,
334     enum gss_eap_token_type tok_type)
335 {
336     *(*buf)++ = 0x60;
337     der_write_length(buf, 4 + mech->length + body_size);
338     *(*buf)++ = 0x06;
339     *(*buf)++ = (unsigned char)mech->length;
340     memcpy(*buf, mech->elements, mech->length);
341     *buf += mech->length;
342     GSSEAP_ASSERT(tok_type != TOK_TYPE_NONE);
343     *(*buf)++ = (unsigned char)((tok_type>>8) & 0xff);
344     *(*buf)++ = (unsigned char)(tok_type & 0xff);
345 }
346
347 /*
348  * Given a buffer containing a token, reads and verifies the token,
349  * leaving buf advanced past the token header, and setting body_size
350  * to the number of remaining bytes.  Returns 0 on success,
351  * G_BAD_TOK_HEADER for a variety of errors, and G_WRONG_MECH if the
352  * mechanism in the token does not match the mech argument.  buf and
353  * *body_size are left unmodified on error.
354  */
355
356 OM_uint32
357 verifyTokenHeader(OM_uint32 *minor,
358                   gss_OID mech,
359                   size_t *body_size,
360                   unsigned char **buf_in,
361                   size_t toksize_in,
362                   enum gss_eap_token_type *ret_tok_type)
363 {
364     unsigned char *buf = *buf_in;
365     ssize_t seqsize;
366     gss_OID_desc toid;
367     ssize_t toksize = (ssize_t)toksize_in;
368
369     *minor = GSSEAP_BAD_TOK_HEADER;
370
371     if (ret_tok_type != NULL)
372         *ret_tok_type = TOK_TYPE_NONE;
373
374     if ((toksize -= 1) < 0)
375         return GSS_S_DEFECTIVE_TOKEN;
376
377     if (*buf++ != 0x60)
378         return GSS_S_DEFECTIVE_TOKEN;
379
380     seqsize = der_read_length(&buf, &toksize);
381     if (seqsize < 0)
382         return GSS_S_DEFECTIVE_TOKEN;
383
384     if (seqsize != toksize)
385         return GSS_S_DEFECTIVE_TOKEN;
386
387     if ((toksize -= 1) < 0)
388         return GSS_S_DEFECTIVE_TOKEN;
389
390     if (*buf++ != 0x06)
391         return GSS_S_DEFECTIVE_TOKEN;
392
393     if ((toksize -= 1) < 0)
394         return GSS_S_DEFECTIVE_TOKEN;
395
396     toid.length = *buf++;
397
398     if ((toksize -= toid.length) < 0)
399         return GSS_S_DEFECTIVE_TOKEN;
400
401     toid.elements = buf;
402     buf += toid.length;
403
404     if (mech->elements == NULL) {
405         *mech = toid;
406         if (toid.length == 0)
407             return GSS_S_BAD_MECH;
408     } else if (!oidEqual(&toid, mech)) {
409         *minor = GSSEAP_WRONG_MECH;
410         return GSS_S_BAD_MECH;
411     }
412
413     if (ret_tok_type != NULL) {
414         if ((toksize -= 2) < 0)
415             return GSS_S_DEFECTIVE_TOKEN;
416
417         *ret_tok_type = load_uint16_be(buf);
418         buf += 2;
419     }
420
421     *buf_in = buf;
422     *body_size = toksize;
423
424     *minor = 0;
425     return GSS_S_COMPLETE;
426 }
427
428 OM_uint32
429 gssEapAllocInnerTokens(OM_uint32 *minor,
430                        size_t count,
431                        struct gss_eap_token_buffer_set *tokens)
432 {
433     OM_uint32 major;
434
435     tokens->buffers.count = 0;
436     tokens->buffers.elements = (gss_buffer_desc *)GSSEAP_CALLOC(count, sizeof(gss_buffer_desc));
437     if (tokens->buffers.elements == NULL) {
438         major = GSS_S_FAILURE;
439         *minor = ENOMEM;
440         goto cleanup;
441     }
442
443     tokens->types = (OM_uint32 *)GSSEAP_CALLOC(count, sizeof(OM_uint32));
444     if (tokens->types == NULL) {
445         major = GSS_S_FAILURE;
446         *minor = ENOMEM;
447         goto cleanup;
448     }
449
450     major = GSS_S_COMPLETE;
451     *minor = 0;
452
453 cleanup:
454     if (GSS_ERROR(major)) {
455         if (tokens->buffers.elements != NULL) {
456             GSSEAP_FREE(tokens->buffers.elements);
457             tokens->buffers.elements = NULL;
458         }
459         if (tokens->types != NULL) {
460             GSSEAP_FREE(tokens->types);
461             tokens->types = NULL;
462         }
463     }
464
465     return major;
466 }
467
468 OM_uint32
469 gssEapReleaseInnerTokens(OM_uint32 *minor,
470                          struct gss_eap_token_buffer_set *tokens,
471                          int freeBuffers)
472 {
473     OM_uint32 tmpMinor;
474     size_t i;
475
476     if (tokens->buffers.elements != NULL) {
477         if (freeBuffers) {
478             for (i = 0; i < tokens->buffers.count; i++)
479                 gss_release_buffer(&tmpMinor, &tokens->buffers.elements[i]);
480         }
481         GSSEAP_FREE(tokens->buffers.elements);
482         tokens->buffers.elements = NULL;
483     }
484     tokens->buffers.count = 0;
485
486     if (tokens->types != NULL) {
487         GSSEAP_FREE(tokens->types);
488         tokens->types = NULL;
489     }
490
491     *minor = 0;
492     return GSS_S_COMPLETE;
493 }