Rearrange moonshot to have libeap as a subproject
[moonshot.git] / moonshot / 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                         gss_buffer_set_t extensions,
63                         OM_uint32 *types,
64                         gss_buffer_t buffer)
65 {
66     OM_uint32 major, tmpMinor;
67     size_t required = 0, i;
68     unsigned char *p;
69
70     buffer->value = NULL;
71     buffer->length = 0;
72
73     if (extensions != GSS_C_NO_BUFFER_SET) {
74         for (i = 0; i < extensions->count; i++) {
75             required += 8 + extensions->elements[i].length;
76         }
77     }
78
79     /*
80      * We must always return a non-NULL token otherwise the calling state
81      * machine assumes we are finished. Hence care in case malloc(0) does
82      * return NULL.
83      */
84     buffer->value = GSSEAP_MALLOC(required ? required : 1);
85     if (buffer->value == NULL) {
86         major = GSS_S_FAILURE;
87         *minor = ENOMEM;
88         goto cleanup;
89     }
90
91     buffer->length = required;
92     p = (unsigned char *)buffer->value;
93
94     if (extensions != GSS_C_NO_BUFFER_SET) {
95         for (i = 0; i < extensions->count; i++) {
96             gss_buffer_t extension = &extensions->elements[i];
97
98             assert((types[i] & ITOK_FLAG_VERIFIED) == 0); /* private flag */
99
100              /*
101               * Extensions are encoded as type-length-value, where the upper
102               * bit of the type indicates criticality.
103               */
104             store_uint32_be(types[i], &p[0]);
105             store_uint32_be(extension->length, &p[4]);
106             memcpy(&p[8], extension->value, extension->length);
107
108             p += 8 + extension->length;
109         }
110     }
111
112     assert(p == (unsigned char *)buffer->value + required);
113     assert(buffer->value != NULL);
114
115     major = GSS_S_COMPLETE;
116     *minor = 0;
117
118 cleanup:
119     if (GSS_ERROR(major)) {
120         gss_release_buffer(&tmpMinor, buffer);
121     }
122
123     return major;
124 }
125
126 OM_uint32
127 gssEapDecodeInnerTokens(OM_uint32 *minor,
128                         const gss_buffer_t buffer,
129                         gss_buffer_set_t *pExtensions,
130                         OM_uint32 **pTypes)
131 {
132     OM_uint32 major, tmpMinor;
133     gss_buffer_set_t extensions = GSS_C_NO_BUFFER_SET;
134     OM_uint32 *types = NULL;
135     unsigned char *p;
136     size_t remain;
137
138     *pExtensions = GSS_C_NO_BUFFER_SET;
139     *pTypes = NULL;
140
141     major = gss_create_empty_buffer_set(minor, &extensions);
142     if (GSS_ERROR(major))
143         goto cleanup;
144
145     if (buffer->length == 0) {
146         major = GSS_S_COMPLETE;
147         goto cleanup;
148     }
149
150     p = (unsigned char *)buffer->value;
151     remain = buffer->length;
152
153     do {
154         OM_uint32 *ntypes;
155         gss_buffer_desc extension;
156
157         if (remain < 8) {
158             major = GSS_S_DEFECTIVE_TOKEN;
159             *minor = GSSEAP_TOK_TRUNC;
160             goto cleanup;
161         }
162
163         ntypes = GSSEAP_REALLOC(types,
164                                 (extensions->count + 1) * sizeof(OM_uint32));
165         if (ntypes == NULL) {
166             major = GSS_S_FAILURE;
167             *minor = ENOMEM;
168             goto cleanup;
169         }
170         types = ntypes;
171
172         types[extensions->count] = load_uint32_be(&p[0]);
173         extension.length = load_uint32_be(&p[4]);
174
175         if (remain < 8 + extension.length) {
176             major = GSS_S_DEFECTIVE_TOKEN;
177             *minor = GSSEAP_TOK_TRUNC;
178             goto cleanup;
179         }
180         extension.value = &p[8];
181
182         major = gss_add_buffer_set_member(minor, &extension, &extensions);
183         if (GSS_ERROR(major))
184             goto cleanup;
185
186         p      += 8 + extension.length;
187         remain -= 8 + extension.length;
188     } while (remain != 0);
189
190 cleanup:
191     if (GSS_ERROR(major)) {
192         gss_release_buffer_set(&tmpMinor, &extensions);
193         if (types != NULL)
194             GSSEAP_FREE(types);
195     } else {
196         *pExtensions = extensions;
197         *pTypes = types;
198     }
199
200     return major;
201 }
202
203 /*
204  * $Id: util_token.c 23457 2009-12-08 00:04:48Z tlyu $
205  */
206
207 /* XXXX this code currently makes the assumption that a mech oid will
208    never be longer than 127 bytes.  This assumption is not inherent in
209    the interfaces, so the code can be fixed if the OSI namespace
210    balloons unexpectedly. */
211
212 /*
213  * Each token looks like this:
214  * 0x60                 tag for APPLICATION 0, SEQUENCE
215  *                              (constructed, definite-length)
216  * <length>             possible multiple bytes, need to parse/generate
217  * 0x06                 tag for OBJECT IDENTIFIER
218  * <moid_length>        compile-time constant string (assume 1 byte)
219  * <moid_bytes>         compile-time constant string
220  * <inner_bytes>        the ANY containing the application token
221  * bytes 0,1 are the token type
222  * bytes 2,n are the token data
223  *
224  * Note that the token type field is a feature of RFC 1964 mechanisms and
225  * is not used by other GSSAPI mechanisms.  As such, a token type of -1
226  * is interpreted to mean that no token type should be expected or
227  * generated.
228  *
229  * For the purposes of this abstraction, the token "header" consists of
230  * the sequence tag and length octets, the mech OID DER encoding, and the
231  * first two inner bytes, which indicate the token type.  The token
232  * "body" consists of everything else.
233  */
234
235 static size_t
236 der_length_size(size_t length)
237 {
238     if (length < (1<<7))
239         return 1;
240     else if (length < (1<<8))
241         return 2;
242 #if INT_MAX == 0x7fff
243     else
244         return 3;
245 #else
246     else if (length < (1<<16))
247         return 3;
248     else if (length < (1<<24))
249         return 4;
250     else
251         return 5;
252 #endif
253 }
254
255 static void
256 der_write_length(unsigned char **buf, size_t length)
257 {
258     if (length < (1<<7)) {
259         *(*buf)++ = (unsigned char)length;
260     } else {
261         *(*buf)++ = (unsigned char)(der_length_size(length)+127);
262 #if INT_MAX > 0x7fff
263         if (length >= (1<<24))
264             *(*buf)++ = (unsigned char)(length>>24);
265         if (length >= (1<<16))
266             *(*buf)++ = (unsigned char)((length>>16)&0xff);
267 #endif
268         if (length >= (1<<8))
269             *(*buf)++ = (unsigned char)((length>>8)&0xff);
270         *(*buf)++ = (unsigned char)(length&0xff);
271     }
272 }
273
274 /* returns decoded length, or < 0 on failure.  Advances buf and
275    decrements bufsize */
276
277 static int
278 der_read_length(unsigned char **buf, ssize_t *bufsize)
279 {
280     unsigned char sf;
281     int ret;
282
283     if (*bufsize < 1)
284         return -1;
285
286     sf = *(*buf)++;
287     (*bufsize)--;
288     if (sf & 0x80) {
289         if ((sf &= 0x7f) > ((*bufsize)-1))
290             return -1;
291         if (sf > sizeof(int))
292             return -1;
293         ret = 0;
294         for (; sf; sf--) {
295             ret = (ret<<8) + (*(*buf)++);
296             (*bufsize)--;
297         }
298     } else {
299         ret = sf;
300     }
301
302     return ret;
303 }
304
305 /* returns the length of a token, given the mech oid and the body size */
306
307 size_t
308 tokenSize(const gss_OID_desc *mech, size_t body_size)
309 {
310     assert(mech != GSS_C_NO_OID);
311
312     /* set body_size to sequence contents size */
313     body_size += 4 + (size_t) mech->length;         /* NEED overflow check */
314     return 1 + der_length_size(body_size) + body_size;
315 }
316
317 /* fills in a buffer with the token header.  The buffer is assumed to
318    be the right size.  buf is advanced past the token header */
319
320 void
321 makeTokenHeader(
322     const gss_OID_desc *mech,
323     size_t body_size,
324     unsigned char **buf,
325     enum gss_eap_token_type tok_type)
326 {
327     *(*buf)++ = 0x60;
328     der_write_length(buf, (tok_type == -1) ?2:4 + mech->length + body_size);
329     *(*buf)++ = 0x06;
330     *(*buf)++ = (unsigned char)mech->length;
331     memcpy(*buf, mech->elements, mech->length);
332     *buf += mech->length;
333     assert(tok_type != TOK_TYPE_NONE);
334     *(*buf)++ = (unsigned char)((tok_type>>8) & 0xff);
335     *(*buf)++ = (unsigned char)(tok_type & 0xff);
336 }
337
338 /*
339  * Given a buffer containing a token, reads and verifies the token,
340  * leaving buf advanced past the token header, and setting body_size
341  * to the number of remaining bytes.  Returns 0 on success,
342  * G_BAD_TOK_HEADER for a variety of errors, and G_WRONG_MECH if the
343  * mechanism in the token does not match the mech argument.  buf and
344  * *body_size are left unmodified on error.
345  */
346
347 OM_uint32
348 verifyTokenHeader(OM_uint32 *minor,
349                   gss_OID mech,
350                   size_t *body_size,
351                   unsigned char **buf_in,
352                   size_t toksize_in,
353                   enum gss_eap_token_type *ret_tok_type)
354 {
355     unsigned char *buf = *buf_in;
356     ssize_t seqsize;
357     gss_OID_desc toid;
358     ssize_t toksize = (ssize_t)toksize_in;
359
360     *minor = GSSEAP_BAD_TOK_HEADER;
361
362     if (ret_tok_type != NULL)
363         *ret_tok_type = TOK_TYPE_NONE;
364
365     if ((toksize -= 1) < 0)
366         return GSS_S_DEFECTIVE_TOKEN;
367
368     if (*buf++ != 0x60)
369         return GSS_S_DEFECTIVE_TOKEN;
370
371     seqsize = der_read_length(&buf, &toksize);
372     if (seqsize < 0)
373         return GSS_S_DEFECTIVE_TOKEN;
374
375     if (seqsize != toksize)
376         return GSS_S_DEFECTIVE_TOKEN;
377
378     if ((toksize -= 1) < 0)
379         return GSS_S_DEFECTIVE_TOKEN;
380
381     if (*buf++ != 0x06)
382         return GSS_S_DEFECTIVE_TOKEN;
383
384     if ((toksize -= 1) < 0)
385         return GSS_S_DEFECTIVE_TOKEN;
386
387     toid.length = *buf++;
388
389     if ((toksize -= toid.length) < 0)
390         return GSS_S_DEFECTIVE_TOKEN;
391
392     toid.elements = buf;
393     buf += toid.length;
394
395     if (mech->elements == NULL) {
396         *mech = toid;
397         if (toid.length == 0)
398             return GSS_S_BAD_MECH;
399     } else if (!oidEqual(&toid, mech)) {
400         *minor = GSSEAP_WRONG_MECH;
401         return GSS_S_BAD_MECH;
402     }
403
404     if (ret_tok_type != NULL) {
405         if ((toksize -= 2) < 0)
406             return GSS_S_DEFECTIVE_TOKEN;
407
408         *ret_tok_type = load_uint16_be(buf);
409         buf += 2;
410     }
411
412     *buf_in = buf;
413     *body_size = toksize;
414
415     *minor = 0;
416     return GSS_S_COMPLETE;
417 }