629117228400a51c7163f67e9f2c87d1a33e4258
[moonshot.git] / moonshot / mech_eap / unwrap_iov.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  * Copyright 2008 by the Massachusetts Institute of Technology.
34  * All Rights Reserved.
35  *
36  * Export of this software from the United States of America may
37  *   require a specific license from the United States Government.
38  *   It is the responsibility of any person or organization contemplating
39  *   export to obtain such a license before exporting.
40  *
41  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
42  * distribute this software and its documentation for any purpose and
43  * without fee is hereby granted, provided that the above copyright
44  * notice appear in all copies and that both that copyright notice and
45  * this permission notice appear in supporting documentation, and that
46  * the name of M.I.T. not be used in advertising or publicity pertaining
47  * to distribution of the software without specific, written prior
48  * permission.  Furthermore if you modify this software you must label
49  * your software as modified software and not distribute it in such a
50  * fashion that it might be confused with the original M.I.T. software.
51  * M.I.T. makes no representations about the suitability of
52  * this software for any purpose.  It is provided "as is" without express
53  * or implied warranty.
54  */
55
56 /*
57  * Message protection services: unwrap with scatter-gather API.
58  */
59
60 #include "gssapiP_eap.h"
61
62 /*
63  * Caller must provide TOKEN | DATA | PADDING | TRAILER, except
64  * for DCE in which case it can just provide TOKEN | DATA (must
65  * guarantee that DATA is padded)
66  */
67 OM_uint32
68 unwrapToken(OM_uint32 *minor,
69             gss_ctx_id_t ctx,
70 #ifdef HAVE_HEIMDAL_VERSION
71             krb5_crypto krbCrypto,
72 #else
73             krb5_keyblock *unused GSSEAP_UNUSED,
74 #endif
75             int *conf_state,
76             gss_qop_t *qop_state,
77             gss_iov_buffer_desc *iov,
78             int iov_count,
79             enum gss_eap_token_type toktype)
80 {
81     OM_uint32 major = GSS_S_FAILURE, code;
82     gss_iov_buffer_t header;
83     gss_iov_buffer_t padding;
84     gss_iov_buffer_t trailer;
85     unsigned char flags;
86     unsigned char *ptr = NULL;
87     int keyUsage;
88     size_t rrc, ec;
89     size_t dataLen, assocDataLen;
90     uint64_t seqnum;
91     int valid = 0;
92     int conf_flag = 0;
93     krb5_context krbContext;
94 #ifdef HAVE_HEIMDAL_VERSION
95     int freeCrypto = (krbCrypto == NULL);
96 #endif
97
98     GSSEAP_KRB_INIT(&krbContext);
99
100     *minor = 0;
101
102     if (qop_state != NULL)
103         *qop_state = GSS_C_QOP_DEFAULT;
104
105     header = gssEapLocateIov(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
106     GSSEAP_ASSERT(header != NULL);
107
108     padding = gssEapLocateIov(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
109     if (padding != NULL && padding->buffer.length != 0) {
110         code = GSSEAP_BAD_PADDING_IOV;
111         major = GSS_S_DEFECTIVE_TOKEN;
112         goto cleanup;
113     }
114
115     trailer = gssEapLocateIov(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
116
117     flags = rfc4121Flags(ctx, TRUE);
118
119     if (toktype == TOK_TYPE_WRAP) {
120         keyUsage = !CTX_IS_INITIATOR(ctx)
121                    ? KEY_USAGE_INITIATOR_SEAL
122                    : KEY_USAGE_ACCEPTOR_SEAL;
123     } else {
124         keyUsage = !CTX_IS_INITIATOR(ctx)
125                    ? KEY_USAGE_INITIATOR_SIGN
126                    : KEY_USAGE_ACCEPTOR_SIGN;
127     }
128
129     gssEapIovMessageLength(iov, iov_count, &dataLen, &assocDataLen);
130
131     ptr = (unsigned char *)header->buffer.value;
132
133     if (header->buffer.length < 16) {
134         code = GSSEAP_TOK_TRUNC;
135         major = GSS_S_DEFECTIVE_TOKEN;
136         goto cleanup;
137     }
138
139     if ((ptr[2] & flags) != flags) {
140         code = GSSEAP_BAD_DIRECTION;
141         major = GSS_S_BAD_SIG;
142         goto cleanup;
143     }
144
145 #ifdef HAVE_HEIMDAL_VERSION
146     if (krbCrypto == NULL) {
147         code = krb5_crypto_init(krbContext, &ctx->rfc3961Key,
148                                 ETYPE_NULL, &krbCrypto);
149         if (code != 0)
150             goto cleanup;
151     }
152 #endif
153
154     if (toktype == TOK_TYPE_WRAP) {
155         size_t krbTrailerLen;
156
157         if (load_uint16_be(ptr) != TOK_TYPE_WRAP)
158             goto defective;
159         conf_flag = ((ptr[2] & TOK_FLAG_WRAP_CONFIDENTIAL) != 0);
160         if (ptr[3] != 0xFF)
161             goto defective;
162         ec = load_uint16_be(ptr + 4);
163         rrc = load_uint16_be(ptr + 6);
164         seqnum = load_uint64_be(ptr + 8);
165
166         code = krbCryptoLength(krbContext, KRB_CRYPTO_CONTEXT(ctx),
167                                conf_flag ? KRB5_CRYPTO_TYPE_TRAILER :
168                                            KRB5_CRYPTO_TYPE_CHECKSUM,
169                                &krbTrailerLen);
170         if (code != 0)
171             goto cleanup;
172
173         /* Deal with RRC */
174         if (trailer == NULL) {
175             size_t desired_rrc = krbTrailerLen;
176
177             if (conf_flag) {
178                 desired_rrc += 16; /* E(Header) */
179
180                 if ((ctx->gssFlags & GSS_C_DCE_STYLE) == 0)
181                     desired_rrc += ec;
182             }
183
184             /* According to MS, we only need to deal with a fixed RRC for DCE */
185             if (rrc != desired_rrc)
186                 goto defective;
187         } else if (rrc != 0) {
188             goto defective;
189         }
190
191         if (conf_flag) {
192             unsigned char *althdr;
193
194             /* Decrypt */
195             code = gssEapDecrypt(krbContext,
196                                  ((ctx->gssFlags & GSS_C_DCE_STYLE) != 0),
197                                  ec, rrc, KRB_CRYPTO_CONTEXT(ctx), keyUsage,
198                                  iov, iov_count);
199             if (code != 0) {
200                 major = GSS_S_BAD_SIG;
201                 goto cleanup;
202             }
203
204             /* Validate header integrity */
205             if (trailer == NULL)
206                 althdr = (unsigned char *)header->buffer.value + 16 + ec;
207             else
208                 althdr = (unsigned char *)trailer->buffer.value + ec;
209
210             if (load_uint16_be(althdr) != TOK_TYPE_WRAP
211                 || althdr[2] != ptr[2]
212                 || althdr[3] != ptr[3]
213                 || memcmp(althdr + 8, ptr + 8, 8) != 0) {
214                 code = GSSEAP_BAD_WRAP_TOKEN;
215                 major = GSS_S_BAD_SIG;
216                 goto cleanup;
217             }
218         } else {
219             /* Verify checksum: note EC is checksum size here, not padding */
220             if (ec != krbTrailerLen)
221                 goto defective;
222
223             /* Zero EC, RRC before computing checksum */
224             store_uint16_be(0, ptr + 4);
225             store_uint16_be(0, ptr + 6);
226
227             code = gssEapVerify(krbContext, ctx->checksumType, rrc,
228                                 KRB_CRYPTO_CONTEXT(ctx), keyUsage,
229                                 iov, iov_count, &valid);
230             if (code != 0 || valid == FALSE) {
231                 major = GSS_S_BAD_SIG;
232                 goto cleanup;
233             }
234         }
235
236         code = sequenceCheck(minor, &ctx->seqState, seqnum);
237     } else if (toktype == TOK_TYPE_MIC) {
238         if (load_uint16_be(ptr) != toktype)
239             goto defective;
240
241     verify_mic_1:
242         if (ptr[3] != 0xFF)
243             goto defective;
244         seqnum = load_uint64_be(ptr + 8);
245
246         code = gssEapVerify(krbContext, ctx->checksumType, 0,
247                             KRB_CRYPTO_CONTEXT(ctx), keyUsage,
248                             iov, iov_count, &valid);
249         if (code != 0 || valid == FALSE) {
250             major = GSS_S_BAD_SIG;
251             goto cleanup;
252         }
253         code = sequenceCheck(minor, &ctx->seqState, seqnum);
254     } else if (toktype == TOK_TYPE_DELETE_CONTEXT) {
255         if (load_uint16_be(ptr) != TOK_TYPE_DELETE_CONTEXT)
256             goto defective;
257         goto verify_mic_1;
258     } else {
259         goto defective;
260     }
261
262     if (conf_state != NULL)
263         *conf_state = conf_flag;
264
265     code = 0;
266     major = GSS_S_COMPLETE;
267     goto cleanup;
268
269 defective:
270     code = GSSEAP_BAD_WRAP_TOKEN;
271     major = GSS_S_DEFECTIVE_TOKEN;
272
273 cleanup:
274     *minor = code;
275 #ifdef HAVE_HEIMDAL_VERSION
276     if (freeCrypto && krbCrypto != NULL)
277         krb5_crypto_destroy(krbContext, krbCrypto);
278 #endif
279
280     return major;
281 }
282
283 int
284 rotateLeft(void *ptr, size_t bufsiz, size_t rc)
285 {
286     void *tbuf;
287
288     if (bufsiz == 0)
289         return 0;
290     rc = rc % bufsiz;
291     if (rc == 0)
292         return 0;
293
294     tbuf = GSSEAP_MALLOC(rc);
295     if (tbuf == NULL)
296         return ENOMEM;
297
298     memcpy(tbuf, ptr, rc);
299     memmove(ptr, (char *)ptr + rc, bufsiz - rc);
300     memcpy((char *)ptr + bufsiz - rc, tbuf, rc);
301     GSSEAP_FREE(tbuf);
302
303     return 0;
304 }
305
306 /*
307  * Split a STREAM | SIGN_DATA | DATA into
308  *         HEADER | SIGN_DATA | DATA | PADDING | TRAILER
309  */
310 static OM_uint32
311 unwrapStream(OM_uint32 *minor,
312              gss_ctx_id_t ctx,
313              int *conf_state,
314              gss_qop_t *qop_state,
315              gss_iov_buffer_desc *iov,
316              int iov_count,
317              enum gss_eap_token_type toktype)
318 {
319     unsigned char *ptr;
320     OM_uint32 code = 0, major = GSS_S_FAILURE;
321     krb5_context krbContext;
322     int conf_req_flag;
323     int i = 0, j;
324     gss_iov_buffer_desc *tiov = NULL;
325     gss_iov_buffer_t stream, data = NULL;
326     gss_iov_buffer_t theader, tdata = NULL, tpadding, ttrailer;
327 #ifdef HAVE_HEIMDAL_VERSION
328     krb5_crypto krbCrypto = NULL;
329 #endif
330
331     GSSEAP_KRB_INIT(&krbContext);
332
333     GSSEAP_ASSERT(toktype == TOK_TYPE_WRAP);
334
335     if (toktype != TOK_TYPE_WRAP) {
336         code = GSSEAP_WRONG_TOK_ID;
337         goto cleanup;
338     }
339
340     stream = gssEapLocateIov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM);
341     GSSEAP_ASSERT(stream != NULL);
342
343     if (stream->buffer.length < 16) {
344         major = GSS_S_DEFECTIVE_TOKEN;
345         goto cleanup;
346     }
347
348     ptr = (unsigned char *)stream->buffer.value;
349     ptr += 2; /* skip token type */
350
351     tiov = (gss_iov_buffer_desc *)GSSEAP_CALLOC((size_t)iov_count + 2,
352                                                 sizeof(gss_iov_buffer_desc));
353     if (tiov == NULL) {
354         code = ENOMEM;
355         goto cleanup;
356     }
357
358     /* HEADER */
359     theader = &tiov[i++];
360     theader->type = GSS_IOV_BUFFER_TYPE_HEADER;
361     theader->buffer.value = stream->buffer.value;
362     theader->buffer.length = 16;
363
364     /* n[SIGN_DATA] | DATA | m[SIGN_DATA] */
365     for (j = 0; j < iov_count; j++) {
366         OM_uint32 type = GSS_IOV_BUFFER_TYPE(iov[j].type);
367
368         if (type == GSS_IOV_BUFFER_TYPE_DATA) {
369             if (data != NULL) {
370                 /* only a single DATA buffer can appear */
371                 code = GSSEAP_BAD_STREAM_IOV;
372                 goto cleanup;
373             }
374
375             data = &iov[j];
376             tdata = &tiov[i];
377         }
378         if (type == GSS_IOV_BUFFER_TYPE_DATA ||
379             type == GSS_IOV_BUFFER_TYPE_SIGN_ONLY)
380             tiov[i++] = iov[j];
381     }
382
383     if (data == NULL) {
384         /* a single DATA buffer must be present */
385         code = GSSEAP_BAD_STREAM_IOV;
386         goto cleanup;
387     }
388
389     /* PADDING | TRAILER */
390     tpadding = &tiov[i++];
391     tpadding->type = GSS_IOV_BUFFER_TYPE_PADDING;
392     tpadding->buffer.length = 0;
393     tpadding->buffer.value = NULL;
394
395     ttrailer = &tiov[i++];
396     ttrailer->type = GSS_IOV_BUFFER_TYPE_TRAILER;
397
398 #ifdef HAVE_HEIMDAL_VERSION
399     code = krb5_crypto_init(krbContext, &ctx->rfc3961Key, ETYPE_NULL, &krbCrypto);
400     if (code != 0)
401         goto cleanup;
402 #endif
403
404     {
405         size_t ec, rrc;
406         size_t krbHeaderLen = 0;
407         size_t krbTrailerLen = 0;
408
409         conf_req_flag = ((ptr[0] & TOK_FLAG_WRAP_CONFIDENTIAL) != 0);
410         ec = conf_req_flag ? load_uint16_be(ptr + 2) : 0;
411         rrc = load_uint16_be(ptr + 4);
412
413         if (rrc != 0) {
414             code = rotateLeft((unsigned char *)stream->buffer.value + 16,
415                               stream->buffer.length - 16, rrc);
416             if (code != 0)
417                 goto cleanup;
418             store_uint16_be(0, ptr + 4); /* set RRC to zero */
419         }
420
421         if (conf_req_flag) {
422             code = krbCryptoLength(krbContext, KRB_CRYPTO_CONTEXT(ctx),
423                                     KRB5_CRYPTO_TYPE_HEADER, &krbHeaderLen);
424             if (code != 0)
425                 goto cleanup;
426             theader->buffer.length += krbHeaderLen; /* length validated later */
427         }
428
429         /* no PADDING for CFX, EC is used instead */
430         code = krbCryptoLength(krbContext, KRB_CRYPTO_CONTEXT(ctx),
431                                conf_req_flag
432                                   ? KRB5_CRYPTO_TYPE_TRAILER
433                                   : KRB5_CRYPTO_TYPE_CHECKSUM,
434                                &krbTrailerLen);
435         if (code != 0)
436             goto cleanup;
437
438         ttrailer->buffer.length = ec + (conf_req_flag ? 16 : 0 /* E(Header) */) +
439                                   krbTrailerLen;
440         ttrailer->buffer.value = (unsigned char *)stream->buffer.value +
441             stream->buffer.length - ttrailer->buffer.length;
442     }
443
444     /* IOV: -----------0-------------+---1---+--2--+----------------3--------------*/
445     /* CFX: GSS-Header | Kerb-Header | Data  |     | EC | E(Header) | Kerb-Trailer */
446     /* GSS: -------GSS-HEADER--------+-DATA--+-PAD-+----------GSS-TRAILER----------*/
447
448     /* validate lengths */
449     if (stream->buffer.length < theader->buffer.length +
450         tpadding->buffer.length +
451         ttrailer->buffer.length) {
452         major = GSS_S_DEFECTIVE_TOKEN;
453         code = GSSEAP_TOK_TRUNC;
454         goto cleanup;
455     }
456
457     /* setup data */
458     tdata->buffer.length = stream->buffer.length - ttrailer->buffer.length -
459         tpadding->buffer.length - theader->buffer.length;
460
461     GSSEAP_ASSERT(data != NULL);
462
463     if (data->type & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
464         code = gssEapAllocIov(tdata, tdata->buffer.length);
465         if (code != 0)
466             goto cleanup;
467
468         memcpy(tdata->buffer.value,
469                (unsigned char *)stream->buffer.value + theader->buffer.length,
470                tdata->buffer.length);
471     } else {
472         tdata->buffer.value = (unsigned char *)stream->buffer.value +
473                               theader->buffer.length;
474     }
475
476     GSSEAP_ASSERT(i <= iov_count + 2);
477
478     major = unwrapToken(&code, ctx, KRB_CRYPTO_CONTEXT(ctx),
479                         conf_state, qop_state, tiov, i, toktype);
480     if (major == GSS_S_COMPLETE) {
481         *data = *tdata;
482     } else if (tdata->type & GSS_IOV_BUFFER_FLAG_ALLOCATED) {
483         OM_uint32 tmp;
484
485         gss_release_buffer(&tmp, &tdata->buffer);
486         tdata->type &= ~(GSS_IOV_BUFFER_FLAG_ALLOCATED);
487     }
488
489 cleanup:
490     if (tiov != NULL)
491         GSSEAP_FREE(tiov);
492 #ifdef HAVE_HEIMDAL_VERSION
493     if (krbCrypto != NULL)
494         krb5_crypto_destroy(krbContext, krbCrypto);
495 #endif
496
497     *minor = code;
498
499     return major;
500 }
501
502 OM_uint32
503 gssEapUnwrapOrVerifyMIC(OM_uint32 *minor,
504                         gss_ctx_id_t ctx,
505                         int *conf_state,
506                         gss_qop_t *qop_state,
507                         gss_iov_buffer_desc *iov,
508                         int iov_count,
509                         enum gss_eap_token_type toktype)
510 {
511     OM_uint32 major;
512
513     if (ctx->encryptionType == ENCTYPE_NULL) {
514         *minor = GSSEAP_KEY_UNAVAILABLE;
515         return GSS_S_UNAVAILABLE;
516     }
517
518     if (gssEapLocateIov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) {
519         major = unwrapStream(minor, ctx, conf_state, qop_state,
520                              iov, iov_count, toktype);
521     } else {
522         major = unwrapToken(minor, ctx,
523                             NULL, /* krbCrypto */
524                             conf_state, qop_state,
525                             iov, iov_count, toktype);
526     }
527
528     return major;
529 }
530
531 OM_uint32 GSSAPI_CALLCONV
532 gss_unwrap_iov(OM_uint32 *minor,
533                gss_ctx_id_t ctx,
534                int *conf_state,
535                gss_qop_t *qop_state,
536                gss_iov_buffer_desc *iov,
537                int iov_count)
538 {
539     OM_uint32 major;
540
541     if (ctx == GSS_C_NO_CONTEXT) {
542         *minor = EINVAL;
543         return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT;
544     }
545
546     *minor = 0;
547
548     GSSEAP_MUTEX_LOCK(&ctx->mutex);
549
550     if (!CTX_IS_ESTABLISHED(ctx)) {
551         major = GSS_S_NO_CONTEXT;
552         *minor = GSSEAP_CONTEXT_INCOMPLETE;
553         goto cleanup;
554     }
555
556     major = gssEapUnwrapOrVerifyMIC(minor, ctx, conf_state, qop_state,
557                                     iov, iov_count, TOK_TYPE_WRAP);
558     if (GSS_ERROR(major))
559         goto cleanup;
560
561 cleanup:
562     GSSEAP_MUTEX_UNLOCK(&ctx->mutex);
563
564     return major;
565 }