os/ossrv/ssl/libssl/src/d1_pkt.c
author sl@SLION-WIN7.fritz.box
Fri, 15 Jun 2012 03:10:57 +0200
changeset 0 bde4ae8d615e
permissions -rw-r--r--
First public contribution.
sl@0
     1
/* ssl/d1_pkt.c */
sl@0
     2
/* 
sl@0
     3
 * DTLS implementation written by Nagendra Modadugu
sl@0
     4
 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
sl@0
     5
 */
sl@0
     6
/* ====================================================================
sl@0
     7
 * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
sl@0
     8
 *
sl@0
     9
 * Redistribution and use in source and binary forms, with or without
sl@0
    10
 * modification, are permitted provided that the following conditions
sl@0
    11
 * are met:
sl@0
    12
 *
sl@0
    13
 * 1. Redistributions of source code must retain the above copyright
sl@0
    14
 *    notice, this list of conditions and the following disclaimer. 
sl@0
    15
 *
sl@0
    16
 * 2. Redistributions in binary form must reproduce the above copyright
sl@0
    17
 *    notice, this list of conditions and the following disclaimer in
sl@0
    18
 *    the documentation and/or other materials provided with the
sl@0
    19
 *    distribution.
sl@0
    20
 *
sl@0
    21
 * 3. All advertising materials mentioning features or use of this
sl@0
    22
 *    software must display the following acknowledgment:
sl@0
    23
 *    "This product includes software developed by the OpenSSL Project
sl@0
    24
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
sl@0
    25
 *
sl@0
    26
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
sl@0
    27
 *    endorse or promote products derived from this software without
sl@0
    28
 *    prior written permission. For written permission, please contact
sl@0
    29
 *    openssl-core@openssl.org.
sl@0
    30
 *
sl@0
    31
 * 5. Products derived from this software may not be called "OpenSSL"
sl@0
    32
 *    nor may "OpenSSL" appear in their names without prior written
sl@0
    33
 *    permission of the OpenSSL Project.
sl@0
    34
 *
sl@0
    35
 * 6. Redistributions of any form whatsoever must retain the following
sl@0
    36
 *    acknowledgment:
sl@0
    37
 *    "This product includes software developed by the OpenSSL Project
sl@0
    38
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
sl@0
    39
 *
sl@0
    40
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
sl@0
    41
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
sl@0
    42
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
sl@0
    43
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
sl@0
    44
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
sl@0
    45
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
sl@0
    46
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
sl@0
    47
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
sl@0
    48
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
sl@0
    49
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
sl@0
    50
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
sl@0
    51
 * OF THE POSSIBILITY OF SUCH DAMAGE.
sl@0
    52
 * ====================================================================
sl@0
    53
 *
sl@0
    54
 * This product includes cryptographic software written by Eric Young
sl@0
    55
 * (eay@cryptsoft.com).  This product includes software written by Tim
sl@0
    56
 * Hudson (tjh@cryptsoft.com).
sl@0
    57
 *
sl@0
    58
 */
sl@0
    59
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
sl@0
    60
 * All rights reserved.
sl@0
    61
 *
sl@0
    62
 * This package is an SSL implementation written
sl@0
    63
 * by Eric Young (eay@cryptsoft.com).
sl@0
    64
 * The implementation was written so as to conform with Netscapes SSL.
sl@0
    65
 * 
sl@0
    66
 * This library is free for commercial and non-commercial use as long as
sl@0
    67
 * the following conditions are aheared to.  The following conditions
sl@0
    68
 * apply to all code found in this distribution, be it the RC4, RSA,
sl@0
    69
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
sl@0
    70
 * included with this distribution is covered by the same copyright terms
sl@0
    71
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
sl@0
    72
 * 
sl@0
    73
 * Copyright remains Eric Young's, and as such any Copyright notices in
sl@0
    74
 * the code are not to be removed.
sl@0
    75
 * If this package is used in a product, Eric Young should be given attribution
sl@0
    76
 * as the author of the parts of the library used.
sl@0
    77
 * This can be in the form of a textual message at program startup or
sl@0
    78
 * in documentation (online or textual) provided with the package.
sl@0
    79
 * 
sl@0
    80
 * Redistribution and use in source and binary forms, with or without
sl@0
    81
 * modification, are permitted provided that the following conditions
sl@0
    82
 * are met:
sl@0
    83
 * 1. Redistributions of source code must retain the copyright
sl@0
    84
 *    notice, this list of conditions and the following disclaimer.
sl@0
    85
 * 2. Redistributions in binary form must reproduce the above copyright
sl@0
    86
 *    notice, this list of conditions and the following disclaimer in the
sl@0
    87
 *    documentation and/or other materials provided with the distribution.
sl@0
    88
 * 3. All advertising materials mentioning features or use of this software
sl@0
    89
 *    must display the following acknowledgement:
sl@0
    90
 *    "This product includes cryptographic software written by
sl@0
    91
 *     Eric Young (eay@cryptsoft.com)"
sl@0
    92
 *    The word 'cryptographic' can be left out if the rouines from the library
sl@0
    93
 *    being used are not cryptographic related :-).
sl@0
    94
 * 4. If you include any Windows specific code (or a derivative thereof) from 
sl@0
    95
 *    the apps directory (application code) you must include an acknowledgement:
sl@0
    96
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
sl@0
    97
 * 
sl@0
    98
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
sl@0
    99
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
sl@0
   100
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
sl@0
   101
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
sl@0
   102
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
sl@0
   103
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
sl@0
   104
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
sl@0
   105
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
sl@0
   106
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
sl@0
   107
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
sl@0
   108
 * SUCH DAMAGE.
sl@0
   109
 * 
sl@0
   110
 * The licence and distribution terms for any publically available version or
sl@0
   111
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
sl@0
   112
 * copied and put under another distribution licence
sl@0
   113
 * [including the GNU Public Licence.]
sl@0
   114
 */
sl@0
   115
sl@0
   116
#include <stdio.h>
sl@0
   117
#include <errno.h>
sl@0
   118
#define USE_SOCKETS
sl@0
   119
#include "ssl_locl.h"
sl@0
   120
#include <openssl/evp.h>
sl@0
   121
#include <openssl/buffer.h>
sl@0
   122
#include <openssl/pqueue.h>
sl@0
   123
#include <openssl/rand.h>
sl@0
   124
sl@0
   125
static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, 
sl@0
   126
	int len, int peek);
sl@0
   127
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
sl@0
   128
	PQ_64BIT *seq_num);
sl@0
   129
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
sl@0
   130
static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, 
sl@0
   131
    unsigned int *is_next_epoch);
sl@0
   132
#if 0
sl@0
   133
static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
sl@0
   134
	unsigned short *priority, unsigned long *offset);
sl@0
   135
#endif
sl@0
   136
static int dtls1_buffer_record(SSL *s, record_pqueue *q,
sl@0
   137
	PQ_64BIT priority);
sl@0
   138
static int dtls1_process_record(SSL *s);
sl@0
   139
#if PQ_64BIT_IS_INTEGER
sl@0
   140
static PQ_64BIT bytes_to_long_long(unsigned char *bytes, PQ_64BIT *num);
sl@0
   141
#endif
sl@0
   142
static void dtls1_clear_timeouts(SSL *s);
sl@0
   143
sl@0
   144
/* copy buffered record into SSL structure */
sl@0
   145
static int
sl@0
   146
dtls1_copy_record(SSL *s, pitem *item)
sl@0
   147
    {
sl@0
   148
    DTLS1_RECORD_DATA *rdata;
sl@0
   149
sl@0
   150
    rdata = (DTLS1_RECORD_DATA *)item->data;
sl@0
   151
    
sl@0
   152
    if (s->s3->rbuf.buf != NULL)
sl@0
   153
        OPENSSL_free(s->s3->rbuf.buf);
sl@0
   154
    
sl@0
   155
    s->packet = rdata->packet;
sl@0
   156
    s->packet_length = rdata->packet_length;
sl@0
   157
    memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
sl@0
   158
    memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
sl@0
   159
    
sl@0
   160
    return(1);
sl@0
   161
    }
sl@0
   162
sl@0
   163
sl@0
   164
static int
sl@0
   165
dtls1_buffer_record(SSL *s, record_pqueue *queue, PQ_64BIT priority)
sl@0
   166
{
sl@0
   167
    DTLS1_RECORD_DATA *rdata;
sl@0
   168
	pitem *item;
sl@0
   169
sl@0
   170
	rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
sl@0
   171
	item = pitem_new(priority, rdata);
sl@0
   172
	if (rdata == NULL || item == NULL)
sl@0
   173
		{
sl@0
   174
		if (rdata != NULL) OPENSSL_free(rdata);
sl@0
   175
		if (item != NULL) pitem_free(item);
sl@0
   176
		
sl@0
   177
		SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
sl@0
   178
		return(0);
sl@0
   179
		}
sl@0
   180
	
sl@0
   181
	rdata->packet = s->packet;
sl@0
   182
	rdata->packet_length = s->packet_length;
sl@0
   183
	memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
sl@0
   184
	memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
sl@0
   185
sl@0
   186
	item->data = rdata;
sl@0
   187
sl@0
   188
	/* insert should not fail, since duplicates are dropped */
sl@0
   189
	if (pqueue_insert(queue->q, item) == NULL)
sl@0
   190
		{
sl@0
   191
		OPENSSL_free(rdata);
sl@0
   192
		pitem_free(item);
sl@0
   193
		return(0);
sl@0
   194
		}
sl@0
   195
sl@0
   196
	s->packet = NULL;
sl@0
   197
	s->packet_length = 0;
sl@0
   198
	memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
sl@0
   199
	memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
sl@0
   200
	
sl@0
   201
	if (!ssl3_setup_buffers(s))
sl@0
   202
		{
sl@0
   203
		SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
sl@0
   204
		OPENSSL_free(rdata);
sl@0
   205
		pitem_free(item);
sl@0
   206
		return(0);
sl@0
   207
		}
sl@0
   208
	
sl@0
   209
	return(1);
sl@0
   210
    }
sl@0
   211
sl@0
   212
sl@0
   213
static int
sl@0
   214
dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
sl@0
   215
    {
sl@0
   216
    pitem *item;
sl@0
   217
sl@0
   218
    item = pqueue_pop(queue->q);
sl@0
   219
    if (item)
sl@0
   220
        {
sl@0
   221
        dtls1_copy_record(s, item);
sl@0
   222
sl@0
   223
        OPENSSL_free(item->data);
sl@0
   224
		pitem_free(item);
sl@0
   225
sl@0
   226
        return(1);
sl@0
   227
        }
sl@0
   228
sl@0
   229
    return(0);
sl@0
   230
    }
sl@0
   231
sl@0
   232
sl@0
   233
/* retrieve a buffered record that belongs to the new epoch, i.e., not processed 
sl@0
   234
 * yet */
sl@0
   235
#define dtls1_get_unprocessed_record(s) \
sl@0
   236
                   dtls1_retrieve_buffered_record((s), \
sl@0
   237
                   &((s)->d1->unprocessed_rcds))
sl@0
   238
sl@0
   239
/* retrieve a buffered record that belongs to the current epoch, ie, processed */
sl@0
   240
#define dtls1_get_processed_record(s) \
sl@0
   241
                   dtls1_retrieve_buffered_record((s), \
sl@0
   242
                   &((s)->d1->processed_rcds))
sl@0
   243
sl@0
   244
static int
sl@0
   245
dtls1_process_buffered_records(SSL *s)
sl@0
   246
    {
sl@0
   247
    pitem *item;
sl@0
   248
    
sl@0
   249
    item = pqueue_peek(s->d1->unprocessed_rcds.q);
sl@0
   250
    if (item)
sl@0
   251
        {
sl@0
   252
        DTLS1_RECORD_DATA *rdata;
sl@0
   253
        rdata = (DTLS1_RECORD_DATA *)item->data;
sl@0
   254
        
sl@0
   255
        /* Check if epoch is current. */
sl@0
   256
        if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
sl@0
   257
            return(1);  /* Nothing to do. */
sl@0
   258
        
sl@0
   259
        /* Process all the records. */
sl@0
   260
        while (pqueue_peek(s->d1->unprocessed_rcds.q))
sl@0
   261
            {
sl@0
   262
            dtls1_get_unprocessed_record(s);
sl@0
   263
            if ( ! dtls1_process_record(s))
sl@0
   264
                return(0);
sl@0
   265
            dtls1_buffer_record(s, &(s->d1->processed_rcds), 
sl@0
   266
                s->s3->rrec.seq_num);
sl@0
   267
            }
sl@0
   268
        }
sl@0
   269
sl@0
   270
    /* sync epoch numbers once all the unprocessed records 
sl@0
   271
     * have been processed */
sl@0
   272
    s->d1->processed_rcds.epoch = s->d1->r_epoch;
sl@0
   273
    s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
sl@0
   274
sl@0
   275
    return(1);
sl@0
   276
    }
sl@0
   277
sl@0
   278
sl@0
   279
#if 0
sl@0
   280
sl@0
   281
static int
sl@0
   282
dtls1_get_buffered_record(SSL *s)
sl@0
   283
	{
sl@0
   284
	pitem *item;
sl@0
   285
	PQ_64BIT priority = 
sl@0
   286
		(((PQ_64BIT)s->d1->handshake_read_seq) << 32) | 
sl@0
   287
		((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
sl@0
   288
	
sl@0
   289
	if ( ! SSL_in_init(s))  /* if we're not (re)negotiating, 
sl@0
   290
							   nothing buffered */
sl@0
   291
		return 0;
sl@0
   292
sl@0
   293
sl@0
   294
	item = pqueue_peek(s->d1->rcvd_records);
sl@0
   295
	if (item && item->priority == priority)
sl@0
   296
		{
sl@0
   297
		/* Check if we've received the record of interest.  It must be
sl@0
   298
		 * a handshake record, since data records as passed up without
sl@0
   299
		 * buffering */
sl@0
   300
		DTLS1_RECORD_DATA *rdata;
sl@0
   301
		item = pqueue_pop(s->d1->rcvd_records);
sl@0
   302
		rdata = (DTLS1_RECORD_DATA *)item->data;
sl@0
   303
		
sl@0
   304
		if (s->s3->rbuf.buf != NULL)
sl@0
   305
			OPENSSL_free(s->s3->rbuf.buf);
sl@0
   306
		
sl@0
   307
		s->packet = rdata->packet;
sl@0
   308
		s->packet_length = rdata->packet_length;
sl@0
   309
		memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
sl@0
   310
		memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
sl@0
   311
		
sl@0
   312
		OPENSSL_free(item->data);
sl@0
   313
		pitem_free(item);
sl@0
   314
		
sl@0
   315
		/* s->d1->next_expected_seq_num++; */
sl@0
   316
		return(1);
sl@0
   317
		}
sl@0
   318
	
sl@0
   319
	return 0;
sl@0
   320
	}
sl@0
   321
sl@0
   322
#endif
sl@0
   323
sl@0
   324
static int
sl@0
   325
dtls1_process_record(SSL *s)
sl@0
   326
{
sl@0
   327
    int i,al;
sl@0
   328
	int clear=0;
sl@0
   329
    int enc_err;
sl@0
   330
	SSL_SESSION *sess;
sl@0
   331
    SSL3_RECORD *rr;
sl@0
   332
	unsigned int mac_size;
sl@0
   333
	unsigned char md[EVP_MAX_MD_SIZE];
sl@0
   334
sl@0
   335
sl@0
   336
	rr= &(s->s3->rrec);
sl@0
   337
    sess = s->session;
sl@0
   338
sl@0
   339
	/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
sl@0
   340
	 * and we have that many bytes in s->packet
sl@0
   341
	 */
sl@0
   342
	rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
sl@0
   343
sl@0
   344
	/* ok, we can now read from 's->packet' data into 'rr'
sl@0
   345
	 * rr->input points at rr->length bytes, which
sl@0
   346
	 * need to be copied into rr->data by either
sl@0
   347
	 * the decryption or by the decompression
sl@0
   348
	 * When the data is 'copied' into the rr->data buffer,
sl@0
   349
	 * rr->input will be pointed at the new buffer */ 
sl@0
   350
sl@0
   351
	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
sl@0
   352
	 * rr->length bytes of encrypted compressed stuff. */
sl@0
   353
sl@0
   354
	/* check is not needed I believe */
sl@0
   355
	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
sl@0
   356
		{
sl@0
   357
		al=SSL_AD_RECORD_OVERFLOW;
sl@0
   358
		SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
sl@0
   359
		goto f_err;
sl@0
   360
		}
sl@0
   361
sl@0
   362
	/* decrypt in place in 'rr->input' */
sl@0
   363
	rr->data=rr->input;
sl@0
   364
sl@0
   365
	enc_err = s->method->ssl3_enc->enc(s,0);
sl@0
   366
	if (enc_err <= 0)
sl@0
   367
		{
sl@0
   368
		if (enc_err == 0)
sl@0
   369
			/* SSLerr() and ssl3_send_alert() have been called */
sl@0
   370
			goto err;
sl@0
   371
sl@0
   372
		/* otherwise enc_err == -1 */
sl@0
   373
		goto decryption_failed_or_bad_record_mac;
sl@0
   374
		}
sl@0
   375
sl@0
   376
#ifdef TLS_DEBUG
sl@0
   377
printf("dec %d\n",rr->length);
sl@0
   378
{ unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
sl@0
   379
printf("\n");
sl@0
   380
#endif
sl@0
   381
sl@0
   382
	/* r->length is now the compressed data plus mac */
sl@0
   383
if (	(sess == NULL) ||
sl@0
   384
		(s->enc_read_ctx == NULL) ||
sl@0
   385
		(s->read_hash == NULL))
sl@0
   386
    clear=1;
sl@0
   387
sl@0
   388
	if (!clear)
sl@0
   389
		{
sl@0
   390
		mac_size=EVP_MD_size(s->read_hash);
sl@0
   391
sl@0
   392
		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
sl@0
   393
			{
sl@0
   394
#if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */
sl@0
   395
			al=SSL_AD_RECORD_OVERFLOW;
sl@0
   396
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
sl@0
   397
			goto f_err;
sl@0
   398
#else
sl@0
   399
			goto decryption_failed_or_bad_record_mac;
sl@0
   400
#endif			
sl@0
   401
			}
sl@0
   402
		/* check the MAC for rr->input (it's in mac_size bytes at the tail) */
sl@0
   403
		if (rr->length < mac_size)
sl@0
   404
			{
sl@0
   405
#if 0 /* OK only for stream ciphers */
sl@0
   406
			al=SSL_AD_DECODE_ERROR;
sl@0
   407
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT);
sl@0
   408
			goto f_err;
sl@0
   409
#else
sl@0
   410
			goto decryption_failed_or_bad_record_mac;
sl@0
   411
#endif
sl@0
   412
			}
sl@0
   413
		rr->length-=mac_size;
sl@0
   414
		i=s->method->ssl3_enc->mac(s,md,0);
sl@0
   415
		if (memcmp(md,&(rr->data[rr->length]),mac_size) != 0)
sl@0
   416
			{
sl@0
   417
			goto decryption_failed_or_bad_record_mac;
sl@0
   418
			}
sl@0
   419
		}
sl@0
   420
sl@0
   421
	/* r->length is now just compressed */
sl@0
   422
	if (s->expand != NULL)
sl@0
   423
		{
sl@0
   424
		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
sl@0
   425
			{
sl@0
   426
			al=SSL_AD_RECORD_OVERFLOW;
sl@0
   427
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
sl@0
   428
			goto f_err;
sl@0
   429
			}
sl@0
   430
		if (!ssl3_do_uncompress(s))
sl@0
   431
			{
sl@0
   432
			al=SSL_AD_DECOMPRESSION_FAILURE;
sl@0
   433
			SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION);
sl@0
   434
			goto f_err;
sl@0
   435
			}
sl@0
   436
		}
sl@0
   437
sl@0
   438
	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
sl@0
   439
		{
sl@0
   440
		al=SSL_AD_RECORD_OVERFLOW;
sl@0
   441
		SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
sl@0
   442
		goto f_err;
sl@0
   443
		}
sl@0
   444
sl@0
   445
	rr->off=0;
sl@0
   446
	/* So at this point the following is true
sl@0
   447
	 * ssl->s3->rrec.type 	is the type of record
sl@0
   448
	 * ssl->s3->rrec.length	== number of bytes in record
sl@0
   449
	 * ssl->s3->rrec.off	== offset to first valid byte
sl@0
   450
	 * ssl->s3->rrec.data	== where to take bytes from, increment
sl@0
   451
	 *			   after use :-).
sl@0
   452
	 */
sl@0
   453
sl@0
   454
	/* we have pulled in a full packet so zero things */
sl@0
   455
	s->packet_length=0;
sl@0
   456
    dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
sl@0
   457
    return(1);
sl@0
   458
sl@0
   459
decryption_failed_or_bad_record_mac:
sl@0
   460
	/* Separate 'decryption_failed' alert was introduced with TLS 1.0,
sl@0
   461
	 * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
sl@0
   462
	 * failure is directly visible from the ciphertext anyway,
sl@0
   463
	 * we should not reveal which kind of error occured -- this
sl@0
   464
	 * might become visible to an attacker (e.g. via logfile) */
sl@0
   465
	al=SSL_AD_BAD_RECORD_MAC;
sl@0
   466
	SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
sl@0
   467
f_err:
sl@0
   468
	ssl3_send_alert(s,SSL3_AL_FATAL,al);
sl@0
   469
err:
sl@0
   470
	return(0);
sl@0
   471
}
sl@0
   472
sl@0
   473
sl@0
   474
/* Call this to get a new input record.
sl@0
   475
 * It will return <= 0 if more data is needed, normally due to an error
sl@0
   476
 * or non-blocking IO.
sl@0
   477
 * When it finishes, one packet has been decoded and can be found in
sl@0
   478
 * ssl->s3->rrec.type    - is the type of record
sl@0
   479
 * ssl->s3->rrec.data, 	 - data
sl@0
   480
 * ssl->s3->rrec.length, - number of bytes
sl@0
   481
 */
sl@0
   482
/* used only by dtls1_read_bytes */
sl@0
   483
int dtls1_get_record(SSL *s)
sl@0
   484
	{
sl@0
   485
	int ssl_major,ssl_minor,al;
sl@0
   486
	int i,n;
sl@0
   487
	SSL3_RECORD *rr;
sl@0
   488
	SSL_SESSION *sess;
sl@0
   489
	unsigned char *p;
sl@0
   490
	unsigned short version;
sl@0
   491
	DTLS1_BITMAP *bitmap;
sl@0
   492
	unsigned int is_next_epoch;
sl@0
   493
sl@0
   494
	rr= &(s->s3->rrec);
sl@0
   495
	sess=s->session;
sl@0
   496
sl@0
   497
    /* The epoch may have changed.  If so, process all the
sl@0
   498
     * pending records.  This is a non-blocking operation. */
sl@0
   499
    if ( ! dtls1_process_buffered_records(s))
sl@0
   500
        return 0;
sl@0
   501
sl@0
   502
	/* if we're renegotiating, then there may be buffered records */
sl@0
   503
	if (dtls1_get_processed_record(s))
sl@0
   504
		return 1;
sl@0
   505
sl@0
   506
	/* get something from the wire */
sl@0
   507
again:
sl@0
   508
	/* check if we have the header */
sl@0
   509
	if (	(s->rstate != SSL_ST_READ_BODY) ||
sl@0
   510
		(s->packet_length < DTLS1_RT_HEADER_LENGTH)) 
sl@0
   511
		{
sl@0
   512
		n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
sl@0
   513
		/* read timeout is handled by dtls1_read_bytes */
sl@0
   514
		if (n <= 0) return(n); /* error or non-blocking */
sl@0
   515
sl@0
   516
		OPENSSL_assert(s->packet_length == DTLS1_RT_HEADER_LENGTH);
sl@0
   517
sl@0
   518
		s->rstate=SSL_ST_READ_BODY;
sl@0
   519
sl@0
   520
		p=s->packet;
sl@0
   521
sl@0
   522
		/* Pull apart the header into the DTLS1_RECORD */
sl@0
   523
		rr->type= *(p++);
sl@0
   524
		ssl_major= *(p++);
sl@0
   525
		ssl_minor= *(p++);
sl@0
   526
		version=(ssl_major<<8)|ssl_minor;
sl@0
   527
sl@0
   528
		/* sequence number is 64 bits, with top 2 bytes = epoch */ 
sl@0
   529
		n2s(p,rr->epoch);
sl@0
   530
sl@0
   531
		memcpy(&(s->s3->read_sequence[2]), p, 6);
sl@0
   532
		p+=6;
sl@0
   533
sl@0
   534
		n2s(p,rr->length);
sl@0
   535
sl@0
   536
		/* Lets check version */
sl@0
   537
		if (!s->first_packet)
sl@0
   538
			{
sl@0
   539
			if (version != s->version && version != DTLS1_BAD_VER)
sl@0
   540
				{
sl@0
   541
				SSLerr(SSL_F_DTLS1_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
sl@0
   542
				/* Send back error using their
sl@0
   543
				 * version number :-) */
sl@0
   544
				s->version=version;
sl@0
   545
				al=SSL_AD_PROTOCOL_VERSION;
sl@0
   546
				goto f_err;
sl@0
   547
				}
sl@0
   548
			}
sl@0
   549
sl@0
   550
		if ((version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
sl@0
   551
		    (version & 0xff00) != (DTLS1_BAD_VER & 0xff00))
sl@0
   552
			{
sl@0
   553
			SSLerr(SSL_F_DTLS1_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
sl@0
   554
			goto err;
sl@0
   555
			}
sl@0
   556
sl@0
   557
		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
sl@0
   558
			{
sl@0
   559
			al=SSL_AD_RECORD_OVERFLOW;
sl@0
   560
			SSLerr(SSL_F_DTLS1_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
sl@0
   561
			goto f_err;
sl@0
   562
			}
sl@0
   563
sl@0
   564
		s->client_version = version;
sl@0
   565
		/* now s->rstate == SSL_ST_READ_BODY */
sl@0
   566
		}
sl@0
   567
sl@0
   568
	/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
sl@0
   569
sl@0
   570
	if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
sl@0
   571
		{
sl@0
   572
		/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
sl@0
   573
		i=rr->length;
sl@0
   574
		n=ssl3_read_n(s,i,i,1);
sl@0
   575
		if (n <= 0) return(n); /* error or non-blocking io */
sl@0
   576
sl@0
   577
		/* this packet contained a partial record, dump it */
sl@0
   578
		if ( n != i)
sl@0
   579
			{
sl@0
   580
			s->packet_length = 0;
sl@0
   581
			goto again;
sl@0
   582
			}
sl@0
   583
sl@0
   584
		/* now n == rr->length,
sl@0
   585
		 * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
sl@0
   586
		}
sl@0
   587
	s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
sl@0
   588
sl@0
   589
	/* match epochs.  NULL means the packet is dropped on the floor */
sl@0
   590
	bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
sl@0
   591
	if ( bitmap == NULL)
sl@0
   592
        {
sl@0
   593
        s->packet_length = 0;  /* dump this record */
sl@0
   594
        goto again;   /* get another record */
sl@0
   595
		}
sl@0
   596
sl@0
   597
	/* check whether this is a repeat, or aged record */
sl@0
   598
	if ( ! dtls1_record_replay_check(s, bitmap, &(rr->seq_num)))
sl@0
   599
		{
sl@0
   600
		s->packet_length=0; /* dump this record */
sl@0
   601
		goto again;     /* get another record */
sl@0
   602
		}
sl@0
   603
sl@0
   604
	/* just read a 0 length packet */
sl@0
   605
	if (rr->length == 0) goto again;
sl@0
   606
sl@0
   607
    /* If this record is from the next epoch (either HM or ALERT), buffer it
sl@0
   608
     * since it cannot be processed at this time.
sl@0
   609
     * Records from the next epoch are marked as received even though they are 
sl@0
   610
     * not processed, so as to prevent any potential resource DoS attack */
sl@0
   611
    if (is_next_epoch)
sl@0
   612
        {
sl@0
   613
        dtls1_record_bitmap_update(s, bitmap);
sl@0
   614
        dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
sl@0
   615
        s->packet_length = 0;
sl@0
   616
        goto again;
sl@0
   617
        }
sl@0
   618
sl@0
   619
    if ( ! dtls1_process_record(s))
sl@0
   620
        return(0);
sl@0
   621
sl@0
   622
	dtls1_clear_timeouts(s);  /* done waiting */
sl@0
   623
	return(1);
sl@0
   624
sl@0
   625
f_err:
sl@0
   626
	ssl3_send_alert(s,SSL3_AL_FATAL,al);
sl@0
   627
err:
sl@0
   628
	return(0);
sl@0
   629
	}
sl@0
   630
sl@0
   631
/* Return up to 'len' payload bytes received in 'type' records.
sl@0
   632
 * 'type' is one of the following:
sl@0
   633
 *
sl@0
   634
 *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
sl@0
   635
 *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
sl@0
   636
 *   -  0 (during a shutdown, no data has to be returned)
sl@0
   637
 *
sl@0
   638
 * If we don't have stored data to work from, read a SSL/TLS record first
sl@0
   639
 * (possibly multiple records if we still don't have anything to return).
sl@0
   640
 *
sl@0
   641
 * This function must handle any surprises the peer may have for us, such as
sl@0
   642
 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
sl@0
   643
 * a surprise, but handled as if it were), or renegotiation requests.
sl@0
   644
 * Also if record payloads contain fragments too small to process, we store
sl@0
   645
 * them until there is enough for the respective protocol (the record protocol
sl@0
   646
 * may use arbitrary fragmentation and even interleaving):
sl@0
   647
 *     Change cipher spec protocol
sl@0
   648
 *             just 1 byte needed, no need for keeping anything stored
sl@0
   649
 *     Alert protocol
sl@0
   650
 *             2 bytes needed (AlertLevel, AlertDescription)
sl@0
   651
 *     Handshake protocol
sl@0
   652
 *             4 bytes needed (HandshakeType, uint24 length) -- we just have
sl@0
   653
 *             to detect unexpected Client Hello and Hello Request messages
sl@0
   654
 *             here, anything else is handled by higher layers
sl@0
   655
 *     Application data protocol
sl@0
   656
 *             none of our business
sl@0
   657
 */
sl@0
   658
int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
sl@0
   659
	{
sl@0
   660
	int al,i,j,ret;
sl@0
   661
	unsigned int n;
sl@0
   662
	SSL3_RECORD *rr;
sl@0
   663
	void (*cb)(const SSL *ssl,int type2,int val)=NULL;
sl@0
   664
sl@0
   665
	if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
sl@0
   666
		if (!ssl3_setup_buffers(s))
sl@0
   667
			return(-1);
sl@0
   668
sl@0
   669
    /* XXX: check what the second '&& type' is about */
sl@0
   670
	if ((type && (type != SSL3_RT_APPLICATION_DATA) && 
sl@0
   671
		(type != SSL3_RT_HANDSHAKE) && type) ||
sl@0
   672
	    (peek && (type != SSL3_RT_APPLICATION_DATA)))
sl@0
   673
		{
sl@0
   674
		SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
sl@0
   675
		return -1;
sl@0
   676
		}
sl@0
   677
sl@0
   678
	/* check whether there's a handshake message (client hello?) waiting */
sl@0
   679
	if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
sl@0
   680
		return ret;
sl@0
   681
sl@0
   682
	/* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
sl@0
   683
sl@0
   684
	if (!s->in_handshake && SSL_in_init(s))
sl@0
   685
		{
sl@0
   686
		/* type == SSL3_RT_APPLICATION_DATA */
sl@0
   687
		i=s->handshake_func(s);
sl@0
   688
		if (i < 0) return(i);
sl@0
   689
		if (i == 0)
sl@0
   690
			{
sl@0
   691
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
sl@0
   692
			return(-1);
sl@0
   693
			}
sl@0
   694
		}
sl@0
   695
sl@0
   696
start:
sl@0
   697
	s->rwstate=SSL_NOTHING;
sl@0
   698
sl@0
   699
	/* s->s3->rrec.type	    - is the type of record
sl@0
   700
	 * s->s3->rrec.data,    - data
sl@0
   701
	 * s->s3->rrec.off,     - offset into 'data' for next read
sl@0
   702
	 * s->s3->rrec.length,  - number of bytes. */
sl@0
   703
	rr = &(s->s3->rrec);
sl@0
   704
sl@0
   705
	/* get new packet if necessary */
sl@0
   706
	if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
sl@0
   707
		{
sl@0
   708
		ret=dtls1_get_record(s);
sl@0
   709
		if (ret <= 0) 
sl@0
   710
			{
sl@0
   711
			ret = dtls1_read_failed(s, ret);
sl@0
   712
			/* anything other than a timeout is an error */
sl@0
   713
			if (ret <= 0)  
sl@0
   714
				return(ret);
sl@0
   715
			else
sl@0
   716
				goto start;
sl@0
   717
			}
sl@0
   718
		}
sl@0
   719
sl@0
   720
	/* we now have a packet which can be read and processed */
sl@0
   721
sl@0
   722
	if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
sl@0
   723
	                               * reset by ssl3_get_finished */
sl@0
   724
		&& (rr->type != SSL3_RT_HANDSHAKE))
sl@0
   725
		{
sl@0
   726
		al=SSL_AD_UNEXPECTED_MESSAGE;
sl@0
   727
		SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
sl@0
   728
		goto err;
sl@0
   729
		}
sl@0
   730
sl@0
   731
	/* If the other end has shut down, throw anything we read away
sl@0
   732
	 * (even in 'peek' mode) */
sl@0
   733
	if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
sl@0
   734
		{
sl@0
   735
		rr->length=0;
sl@0
   736
		s->rwstate=SSL_NOTHING;
sl@0
   737
		return(0);
sl@0
   738
		}
sl@0
   739
sl@0
   740
sl@0
   741
	if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
sl@0
   742
		{
sl@0
   743
		/* make sure that we are not getting application data when we
sl@0
   744
		 * are doing a handshake for the first time */
sl@0
   745
		if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
sl@0
   746
			(s->enc_read_ctx == NULL))
sl@0
   747
			{
sl@0
   748
			al=SSL_AD_UNEXPECTED_MESSAGE;
sl@0
   749
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
sl@0
   750
			goto f_err;
sl@0
   751
			}
sl@0
   752
sl@0
   753
		if (len <= 0) return(len);
sl@0
   754
sl@0
   755
		if ((unsigned int)len > rr->length)
sl@0
   756
			n = rr->length;
sl@0
   757
		else
sl@0
   758
			n = (unsigned int)len;
sl@0
   759
sl@0
   760
		memcpy(buf,&(rr->data[rr->off]),n);
sl@0
   761
		if (!peek)
sl@0
   762
			{
sl@0
   763
			rr->length-=n;
sl@0
   764
			rr->off+=n;
sl@0
   765
			if (rr->length == 0)
sl@0
   766
				{
sl@0
   767
				s->rstate=SSL_ST_READ_HEADER;
sl@0
   768
				rr->off=0;
sl@0
   769
				}
sl@0
   770
			}
sl@0
   771
		return(n);
sl@0
   772
		}
sl@0
   773
sl@0
   774
sl@0
   775
	/* If we get here, then type != rr->type; if we have a handshake
sl@0
   776
	 * message, then it was unexpected (Hello Request or Client Hello). */
sl@0
   777
sl@0
   778
	/* In case of record types for which we have 'fragment' storage,
sl@0
   779
	 * fill that so that we can process the data at a fixed place.
sl@0
   780
	 */
sl@0
   781
		{
sl@0
   782
		unsigned int k, dest_maxlen = 0;
sl@0
   783
		unsigned char *dest = NULL;
sl@0
   784
		unsigned int *dest_len = NULL;
sl@0
   785
sl@0
   786
		if (rr->type == SSL3_RT_HANDSHAKE)
sl@0
   787
			{
sl@0
   788
			dest_maxlen = sizeof s->d1->handshake_fragment;
sl@0
   789
			dest = s->d1->handshake_fragment;
sl@0
   790
			dest_len = &s->d1->handshake_fragment_len;
sl@0
   791
			}
sl@0
   792
		else if (rr->type == SSL3_RT_ALERT)
sl@0
   793
			{
sl@0
   794
			dest_maxlen = sizeof(s->d1->alert_fragment);
sl@0
   795
			dest = s->d1->alert_fragment;
sl@0
   796
			dest_len = &s->d1->alert_fragment_len;
sl@0
   797
			}
sl@0
   798
                /* else it's a CCS message, or it's wrong */
sl@0
   799
                else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
sl@0
   800
                        {
sl@0
   801
                          /* Not certain if this is the right error handling */
sl@0
   802
                          al=SSL_AD_UNEXPECTED_MESSAGE;
sl@0
   803
                          SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
sl@0
   804
                          goto f_err;
sl@0
   805
                        }
sl@0
   806
sl@0
   807
sl@0
   808
		if (dest_maxlen > 0)
sl@0
   809
			{
sl@0
   810
            /* XDTLS:  In a pathalogical case, the Client Hello
sl@0
   811
             *  may be fragmented--don't always expect dest_maxlen bytes */
sl@0
   812
			if ( rr->length < dest_maxlen)
sl@0
   813
				{
sl@0
   814
				s->rstate=SSL_ST_READ_HEADER;
sl@0
   815
				rr->length = 0;
sl@0
   816
				goto start;
sl@0
   817
				}
sl@0
   818
sl@0
   819
			/* now move 'n' bytes: */
sl@0
   820
			for ( k = 0; k < dest_maxlen; k++)
sl@0
   821
				{
sl@0
   822
				dest[k] = rr->data[rr->off++];
sl@0
   823
				rr->length--;
sl@0
   824
				}
sl@0
   825
			*dest_len = dest_maxlen;
sl@0
   826
			}
sl@0
   827
		}
sl@0
   828
sl@0
   829
	/* s->d1->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
sl@0
   830
	 * s->d1->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
sl@0
   831
	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
sl@0
   832
sl@0
   833
	/* If we are a client, check for an incoming 'Hello Request': */
sl@0
   834
	if ((!s->server) &&
sl@0
   835
		(s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
sl@0
   836
		(s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
sl@0
   837
		(s->session != NULL) && (s->session->cipher != NULL))
sl@0
   838
		{
sl@0
   839
		s->d1->handshake_fragment_len = 0;
sl@0
   840
sl@0
   841
		if ((s->d1->handshake_fragment[1] != 0) ||
sl@0
   842
			(s->d1->handshake_fragment[2] != 0) ||
sl@0
   843
			(s->d1->handshake_fragment[3] != 0))
sl@0
   844
			{
sl@0
   845
			al=SSL_AD_DECODE_ERROR;
sl@0
   846
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
sl@0
   847
			goto err;
sl@0
   848
			}
sl@0
   849
sl@0
   850
		/* no need to check sequence number on HELLO REQUEST messages */
sl@0
   851
sl@0
   852
		if (s->msg_callback)
sl@0
   853
			s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, 
sl@0
   854
				s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
sl@0
   855
sl@0
   856
		if (SSL_is_init_finished(s) &&
sl@0
   857
			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
sl@0
   858
			!s->s3->renegotiate)
sl@0
   859
			{
sl@0
   860
			ssl3_renegotiate(s);
sl@0
   861
			if (ssl3_renegotiate_check(s))
sl@0
   862
				{
sl@0
   863
				i=s->handshake_func(s);
sl@0
   864
				if (i < 0) return(i);
sl@0
   865
				if (i == 0)
sl@0
   866
					{
sl@0
   867
					SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
sl@0
   868
					return(-1);
sl@0
   869
					}
sl@0
   870
sl@0
   871
				if (!(s->mode & SSL_MODE_AUTO_RETRY))
sl@0
   872
					{
sl@0
   873
					if (s->s3->rbuf.left == 0) /* no read-ahead left? */
sl@0
   874
						{
sl@0
   875
						BIO *bio;
sl@0
   876
						/* In the case where we try to read application data,
sl@0
   877
						 * but we trigger an SSL handshake, we return -1 with
sl@0
   878
						 * the retry option set.  Otherwise renegotiation may
sl@0
   879
						 * cause nasty problems in the blocking world */
sl@0
   880
						s->rwstate=SSL_READING;
sl@0
   881
						bio=SSL_get_rbio(s);
sl@0
   882
						BIO_clear_retry_flags(bio);
sl@0
   883
						BIO_set_retry_read(bio);
sl@0
   884
						return(-1);
sl@0
   885
						}
sl@0
   886
					}
sl@0
   887
				}
sl@0
   888
			}
sl@0
   889
		/* we either finished a handshake or ignored the request,
sl@0
   890
		 * now try again to obtain the (application) data we were asked for */
sl@0
   891
		goto start;
sl@0
   892
		}
sl@0
   893
sl@0
   894
	if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
sl@0
   895
		{
sl@0
   896
		int alert_level = s->d1->alert_fragment[0];
sl@0
   897
		int alert_descr = s->d1->alert_fragment[1];
sl@0
   898
sl@0
   899
		s->d1->alert_fragment_len = 0;
sl@0
   900
sl@0
   901
		if (s->msg_callback)
sl@0
   902
			s->msg_callback(0, s->version, SSL3_RT_ALERT, 
sl@0
   903
				s->d1->alert_fragment, 2, s, s->msg_callback_arg);
sl@0
   904
sl@0
   905
		if (s->info_callback != NULL)
sl@0
   906
			cb=s->info_callback;
sl@0
   907
		else if (s->ctx->info_callback != NULL)
sl@0
   908
			cb=s->ctx->info_callback;
sl@0
   909
sl@0
   910
		if (cb != NULL)
sl@0
   911
			{
sl@0
   912
			j = (alert_level << 8) | alert_descr;
sl@0
   913
			cb(s, SSL_CB_READ_ALERT, j);
sl@0
   914
			}
sl@0
   915
sl@0
   916
		if (alert_level == 1) /* warning */
sl@0
   917
			{
sl@0
   918
			s->s3->warn_alert = alert_descr;
sl@0
   919
			if (alert_descr == SSL_AD_CLOSE_NOTIFY)
sl@0
   920
				{
sl@0
   921
				s->shutdown |= SSL_RECEIVED_SHUTDOWN;
sl@0
   922
				return(0);
sl@0
   923
				}
sl@0
   924
#if 0
sl@0
   925
            /* XXX: this is a possible improvement in the future */
sl@0
   926
			/* now check if it's a missing record */
sl@0
   927
			if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
sl@0
   928
				{
sl@0
   929
				unsigned short seq;
sl@0
   930
				unsigned int frag_off;
sl@0
   931
				unsigned char *p = &(s->d1->alert_fragment[2]);
sl@0
   932
sl@0
   933
				n2s(p, seq);
sl@0
   934
				n2l3(p, frag_off);
sl@0
   935
sl@0
   936
				dtls1_retransmit_message(s, seq, frag_off, &found);
sl@0
   937
				if ( ! found  && SSL_in_init(s))
sl@0
   938
					{
sl@0
   939
					/* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */
sl@0
   940
					/* requested a message not yet sent, 
sl@0
   941
					   send an alert ourselves */
sl@0
   942
					ssl3_send_alert(s,SSL3_AL_WARNING,
sl@0
   943
						DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
sl@0
   944
					}
sl@0
   945
				}
sl@0
   946
#endif
sl@0
   947
			}
sl@0
   948
		else if (alert_level == 2) /* fatal */
sl@0
   949
			{
sl@0
   950
			char tmp[16];
sl@0
   951
sl@0
   952
			s->rwstate=SSL_NOTHING;
sl@0
   953
			s->s3->fatal_alert = alert_descr;
sl@0
   954
			SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
sl@0
   955
			BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
sl@0
   956
			ERR_add_error_data(2,"SSL alert number ",tmp);
sl@0
   957
			s->shutdown|=SSL_RECEIVED_SHUTDOWN;
sl@0
   958
			SSL_CTX_remove_session(s->ctx,s->session);
sl@0
   959
			return(0);
sl@0
   960
			}
sl@0
   961
		else
sl@0
   962
			{
sl@0
   963
			al=SSL_AD_ILLEGAL_PARAMETER;
sl@0
   964
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
sl@0
   965
			goto f_err;
sl@0
   966
			}
sl@0
   967
sl@0
   968
		goto start;
sl@0
   969
		}
sl@0
   970
sl@0
   971
	if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
sl@0
   972
		{
sl@0
   973
		s->rwstate=SSL_NOTHING;
sl@0
   974
		rr->length=0;
sl@0
   975
		return(0);
sl@0
   976
		}
sl@0
   977
sl@0
   978
	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
sl@0
   979
		{
sl@0
   980
		struct ccs_header_st ccs_hdr;
sl@0
   981
sl@0
   982
		dtls1_get_ccs_header(rr->data, &ccs_hdr);
sl@0
   983
sl@0
   984
		/* 'Change Cipher Spec' is just a single byte, so we know
sl@0
   985
		 * exactly what the record payload has to look like */
sl@0
   986
		/* XDTLS: check that epoch is consistent */
sl@0
   987
		if (	(s->client_version == DTLS1_BAD_VER && rr->length != 3) ||
sl@0
   988
			(s->client_version != DTLS1_BAD_VER && rr->length != DTLS1_CCS_HEADER_LENGTH) || 
sl@0
   989
			(rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
sl@0
   990
			{
sl@0
   991
			i=SSL_AD_ILLEGAL_PARAMETER;
sl@0
   992
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
sl@0
   993
			goto err;
sl@0
   994
			}
sl@0
   995
sl@0
   996
		rr->length=0;
sl@0
   997
sl@0
   998
		if (s->msg_callback)
sl@0
   999
			s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, 
sl@0
  1000
				rr->data, 1, s, s->msg_callback_arg);
sl@0
  1001
sl@0
  1002
		s->s3->change_cipher_spec=1;
sl@0
  1003
		if (!ssl3_do_change_cipher_spec(s))
sl@0
  1004
			goto err;
sl@0
  1005
sl@0
  1006
		/* do this whenever CCS is processed */
sl@0
  1007
		dtls1_reset_seq_numbers(s, SSL3_CC_READ);
sl@0
  1008
sl@0
  1009
		if (s->client_version == DTLS1_BAD_VER)
sl@0
  1010
			s->d1->handshake_read_seq++;
sl@0
  1011
sl@0
  1012
		goto start;
sl@0
  1013
		}
sl@0
  1014
sl@0
  1015
	/* Unexpected handshake message (Client Hello, or protocol violation) */
sl@0
  1016
	if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 
sl@0
  1017
		!s->in_handshake)
sl@0
  1018
		{
sl@0
  1019
		struct hm_header_st msg_hdr;
sl@0
  1020
		
sl@0
  1021
		/* this may just be a stale retransmit */
sl@0
  1022
		dtls1_get_message_header(rr->data, &msg_hdr);
sl@0
  1023
		if( rr->epoch != s->d1->r_epoch)
sl@0
  1024
			{
sl@0
  1025
			rr->length = 0;
sl@0
  1026
			goto start;
sl@0
  1027
			}
sl@0
  1028
sl@0
  1029
		if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
sl@0
  1030
			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
sl@0
  1031
			{
sl@0
  1032
#if 0 /* worked only because C operator preferences are not as expected (and
sl@0
  1033
       * because this is not really needed for clients except for detecting
sl@0
  1034
       * protocol violations): */
sl@0
  1035
			s->state=SSL_ST_BEFORE|(s->server)
sl@0
  1036
				?SSL_ST_ACCEPT
sl@0
  1037
				:SSL_ST_CONNECT;
sl@0
  1038
#else
sl@0
  1039
			s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
sl@0
  1040
#endif
sl@0
  1041
			s->new_session=1;
sl@0
  1042
			}
sl@0
  1043
		i=s->handshake_func(s);
sl@0
  1044
		if (i < 0) return(i);
sl@0
  1045
		if (i == 0)
sl@0
  1046
			{
sl@0
  1047
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
sl@0
  1048
			return(-1);
sl@0
  1049
			}
sl@0
  1050
sl@0
  1051
		if (!(s->mode & SSL_MODE_AUTO_RETRY))
sl@0
  1052
			{
sl@0
  1053
			if (s->s3->rbuf.left == 0) /* no read-ahead left? */
sl@0
  1054
				{
sl@0
  1055
				BIO *bio;
sl@0
  1056
				/* In the case where we try to read application data,
sl@0
  1057
				 * but we trigger an SSL handshake, we return -1 with
sl@0
  1058
				 * the retry option set.  Otherwise renegotiation may
sl@0
  1059
				 * cause nasty problems in the blocking world */
sl@0
  1060
				s->rwstate=SSL_READING;
sl@0
  1061
				bio=SSL_get_rbio(s);
sl@0
  1062
				BIO_clear_retry_flags(bio);
sl@0
  1063
				BIO_set_retry_read(bio);
sl@0
  1064
				return(-1);
sl@0
  1065
				}
sl@0
  1066
			}
sl@0
  1067
		goto start;
sl@0
  1068
		}
sl@0
  1069
sl@0
  1070
	switch (rr->type)
sl@0
  1071
		{
sl@0
  1072
	default:
sl@0
  1073
#ifndef OPENSSL_NO_TLS
sl@0
  1074
		/* TLS just ignores unknown message types */
sl@0
  1075
		if (s->version == TLS1_VERSION)
sl@0
  1076
			{
sl@0
  1077
			rr->length = 0;
sl@0
  1078
			goto start;
sl@0
  1079
			}
sl@0
  1080
#endif
sl@0
  1081
		al=SSL_AD_UNEXPECTED_MESSAGE;
sl@0
  1082
		SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
sl@0
  1083
		goto f_err;
sl@0
  1084
	case SSL3_RT_CHANGE_CIPHER_SPEC:
sl@0
  1085
	case SSL3_RT_ALERT:
sl@0
  1086
	case SSL3_RT_HANDSHAKE:
sl@0
  1087
		/* we already handled all of these, with the possible exception
sl@0
  1088
		 * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
sl@0
  1089
		 * should not happen when type != rr->type */
sl@0
  1090
		al=SSL_AD_UNEXPECTED_MESSAGE;
sl@0
  1091
		SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR);
sl@0
  1092
		goto f_err;
sl@0
  1093
	case SSL3_RT_APPLICATION_DATA:
sl@0
  1094
		/* At this point, we were expecting handshake data,
sl@0
  1095
		 * but have application data.  If the library was
sl@0
  1096
		 * running inside ssl3_read() (i.e. in_read_app_data
sl@0
  1097
		 * is set) and it makes sense to read application data
sl@0
  1098
		 * at this point (session renegotiation not yet started),
sl@0
  1099
		 * we will indulge it.
sl@0
  1100
		 */
sl@0
  1101
		if (s->s3->in_read_app_data &&
sl@0
  1102
			(s->s3->total_renegotiations != 0) &&
sl@0
  1103
			((
sl@0
  1104
				(s->state & SSL_ST_CONNECT) &&
sl@0
  1105
				(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
sl@0
  1106
				(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
sl@0
  1107
				) || (
sl@0
  1108
					(s->state & SSL_ST_ACCEPT) &&
sl@0
  1109
					(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
sl@0
  1110
					(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
sl@0
  1111
					)
sl@0
  1112
				))
sl@0
  1113
			{
sl@0
  1114
			s->s3->in_read_app_data=2;
sl@0
  1115
			return(-1);
sl@0
  1116
			}
sl@0
  1117
		else
sl@0
  1118
			{
sl@0
  1119
			al=SSL_AD_UNEXPECTED_MESSAGE;
sl@0
  1120
			SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
sl@0
  1121
			goto f_err;
sl@0
  1122
			}
sl@0
  1123
		}
sl@0
  1124
	/* not reached */
sl@0
  1125
sl@0
  1126
f_err:
sl@0
  1127
	ssl3_send_alert(s,SSL3_AL_FATAL,al);
sl@0
  1128
err:
sl@0
  1129
	return(-1);
sl@0
  1130
	}
sl@0
  1131
sl@0
  1132
int
sl@0
  1133
dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
sl@0
  1134
	{
sl@0
  1135
	unsigned int n,tot;
sl@0
  1136
	int i;
sl@0
  1137
sl@0
  1138
	if (SSL_in_init(s) && !s->in_handshake)
sl@0
  1139
		{
sl@0
  1140
		i=s->handshake_func(s);
sl@0
  1141
		if (i < 0) return(i);
sl@0
  1142
		if (i == 0)
sl@0
  1143
			{
sl@0
  1144
			SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
sl@0
  1145
			return -1;
sl@0
  1146
			}
sl@0
  1147
		}
sl@0
  1148
sl@0
  1149
	tot = s->s3->wnum;
sl@0
  1150
	n = len - tot;
sl@0
  1151
sl@0
  1152
	while( n)
sl@0
  1153
		{
sl@0
  1154
		/* dtls1_write_bytes sends one record at a time, sized according to 
sl@0
  1155
		 * the currently known MTU */
sl@0
  1156
		i = dtls1_write_bytes(s, type, buf_, len);
sl@0
  1157
		if (i <= 0) return i;
sl@0
  1158
		
sl@0
  1159
		if ((i == (int)n) ||
sl@0
  1160
			(type == SSL3_RT_APPLICATION_DATA &&
sl@0
  1161
				(s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
sl@0
  1162
			{
sl@0
  1163
			/* next chunk of data should get another prepended empty fragment
sl@0
  1164
			 * in ciphersuites with known-IV weakness: */
sl@0
  1165
			s->s3->empty_fragment_done = 0;
sl@0
  1166
			return tot+i;
sl@0
  1167
			}
sl@0
  1168
sl@0
  1169
		tot += i;
sl@0
  1170
		n-=i;
sl@0
  1171
		}
sl@0
  1172
sl@0
  1173
	return tot;
sl@0
  1174
	}
sl@0
  1175
sl@0
  1176
sl@0
  1177
	/* this only happens when a client hello is received and a handshake 
sl@0
  1178
	 * is started. */
sl@0
  1179
static int
sl@0
  1180
have_handshake_fragment(SSL *s, int type, unsigned char *buf, 
sl@0
  1181
	int len, int peek)
sl@0
  1182
	{
sl@0
  1183
	
sl@0
  1184
	if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
sl@0
  1185
		/* (partially) satisfy request from storage */
sl@0
  1186
		{
sl@0
  1187
		unsigned char *src = s->d1->handshake_fragment;
sl@0
  1188
		unsigned char *dst = buf;
sl@0
  1189
		unsigned int k,n;
sl@0
  1190
		
sl@0
  1191
		/* peek == 0 */
sl@0
  1192
		n = 0;
sl@0
  1193
		while ((len > 0) && (s->d1->handshake_fragment_len > 0))
sl@0
  1194
			{
sl@0
  1195
			*dst++ = *src++;
sl@0
  1196
			len--; s->d1->handshake_fragment_len--;
sl@0
  1197
			n++;
sl@0
  1198
			}
sl@0
  1199
		/* move any remaining fragment bytes: */
sl@0
  1200
		for (k = 0; k < s->d1->handshake_fragment_len; k++)
sl@0
  1201
			s->d1->handshake_fragment[k] = *src++;
sl@0
  1202
		return n;
sl@0
  1203
		}
sl@0
  1204
	
sl@0
  1205
	return 0;
sl@0
  1206
	}
sl@0
  1207
sl@0
  1208
sl@0
  1209
sl@0
  1210
sl@0
  1211
/* Call this to write data in records of type 'type'
sl@0
  1212
 * It will return <= 0 if not all data has been sent or non-blocking IO.
sl@0
  1213
 */
sl@0
  1214
int dtls1_write_bytes(SSL *s, int type, const void *buf_, int len)
sl@0
  1215
	{
sl@0
  1216
	const unsigned char *buf=buf_;
sl@0
  1217
	unsigned int tot,n,nw;
sl@0
  1218
	int i;
sl@0
  1219
	unsigned int mtu;
sl@0
  1220
sl@0
  1221
	s->rwstate=SSL_NOTHING;
sl@0
  1222
	tot=s->s3->wnum;
sl@0
  1223
sl@0
  1224
	n=(len-tot);
sl@0
  1225
sl@0
  1226
	/* handshake layer figures out MTU for itself, but data records
sl@0
  1227
	 * are also sent through this interface, so need to figure out MTU */
sl@0
  1228
#if 0
sl@0
  1229
	mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_MTU, 0, NULL);
sl@0
  1230
	mtu += DTLS1_HM_HEADER_LENGTH;  /* HM already inserted */
sl@0
  1231
#endif
sl@0
  1232
	mtu = s->d1->mtu;
sl@0
  1233
sl@0
  1234
	if (mtu > SSL3_RT_MAX_PLAIN_LENGTH)
sl@0
  1235
		mtu = SSL3_RT_MAX_PLAIN_LENGTH;
sl@0
  1236
sl@0
  1237
	if (n > mtu)
sl@0
  1238
		nw=mtu;
sl@0
  1239
	else
sl@0
  1240
		nw=n;
sl@0
  1241
	
sl@0
  1242
	i=do_dtls1_write(s, type, &(buf[tot]), nw, 0);
sl@0
  1243
	if (i <= 0)
sl@0
  1244
		{
sl@0
  1245
		s->s3->wnum=tot;
sl@0
  1246
		return i;
sl@0
  1247
		}
sl@0
  1248
sl@0
  1249
	if ( (int)s->s3->wnum + i == len)
sl@0
  1250
		s->s3->wnum = 0;
sl@0
  1251
	else 
sl@0
  1252
		s->s3->wnum += i;
sl@0
  1253
sl@0
  1254
	return tot + i;
sl@0
  1255
	}
sl@0
  1256
sl@0
  1257
int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment)
sl@0
  1258
	{
sl@0
  1259
	unsigned char *p,*pseq;
sl@0
  1260
	int i,mac_size,clear=0;
sl@0
  1261
	int prefix_len = 0;
sl@0
  1262
	SSL3_RECORD *wr;
sl@0
  1263
	SSL3_BUFFER *wb;
sl@0
  1264
	SSL_SESSION *sess;
sl@0
  1265
	int bs;
sl@0
  1266
sl@0
  1267
	/* first check if there is a SSL3_BUFFER still being written
sl@0
  1268
	 * out.  This will happen with non blocking IO */
sl@0
  1269
	if (s->s3->wbuf.left != 0)
sl@0
  1270
		{
sl@0
  1271
		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
sl@0
  1272
		return(ssl3_write_pending(s,type,buf,len));
sl@0
  1273
		}
sl@0
  1274
sl@0
  1275
	/* If we have an alert to send, lets send it */
sl@0
  1276
	if (s->s3->alert_dispatch)
sl@0
  1277
		{
sl@0
  1278
		i=s->method->ssl_dispatch_alert(s);
sl@0
  1279
		if (i <= 0)
sl@0
  1280
			return(i);
sl@0
  1281
		/* if it went, fall through and send more stuff */
sl@0
  1282
		}
sl@0
  1283
sl@0
  1284
	if (len == 0 && !create_empty_fragment)
sl@0
  1285
		return 0;
sl@0
  1286
sl@0
  1287
	wr= &(s->s3->wrec);
sl@0
  1288
	wb= &(s->s3->wbuf);
sl@0
  1289
	sess=s->session;
sl@0
  1290
sl@0
  1291
	if (	(sess == NULL) ||
sl@0
  1292
		(s->enc_write_ctx == NULL) ||
sl@0
  1293
		(s->write_hash == NULL))
sl@0
  1294
		clear=1;
sl@0
  1295
sl@0
  1296
	if (clear)
sl@0
  1297
		mac_size=0;
sl@0
  1298
	else
sl@0
  1299
		mac_size=EVP_MD_size(s->write_hash);
sl@0
  1300
sl@0
  1301
	/* DTLS implements explicit IV, so no need for empty fragments */
sl@0
  1302
#if 0
sl@0
  1303
	/* 'create_empty_fragment' is true only when this function calls itself */
sl@0
  1304
	if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
sl@0
  1305
		&& SSL_version(s) != DTLS1_VERSION)
sl@0
  1306
		{
sl@0
  1307
		/* countermeasure against known-IV weakness in CBC ciphersuites
sl@0
  1308
		 * (see http://www.openssl.org/~bodo/tls-cbc.txt) 
sl@0
  1309
		 */
sl@0
  1310
sl@0
  1311
		if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
sl@0
  1312
			{
sl@0
  1313
			/* recursive function call with 'create_empty_fragment' set;
sl@0
  1314
			 * this prepares and buffers the data for an empty fragment
sl@0
  1315
			 * (these 'prefix_len' bytes are sent out later
sl@0
  1316
			 * together with the actual payload) */
sl@0
  1317
			prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
sl@0
  1318
			if (prefix_len <= 0)
sl@0
  1319
				goto err;
sl@0
  1320
sl@0
  1321
			if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE)
sl@0
  1322
				{
sl@0
  1323
				/* insufficient space */
sl@0
  1324
				SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
sl@0
  1325
				goto err;
sl@0
  1326
				}
sl@0
  1327
			}
sl@0
  1328
		
sl@0
  1329
		s->s3->empty_fragment_done = 1;
sl@0
  1330
		}
sl@0
  1331
#endif
sl@0
  1332
sl@0
  1333
	p = wb->buf + prefix_len;
sl@0
  1334
sl@0
  1335
	/* write the header */
sl@0
  1336
sl@0
  1337
	*(p++)=type&0xff;
sl@0
  1338
	wr->type=type;
sl@0
  1339
sl@0
  1340
	if (s->client_version == DTLS1_BAD_VER)
sl@0
  1341
		*(p++) = DTLS1_BAD_VER>>8,
sl@0
  1342
		*(p++) = DTLS1_BAD_VER&0xff;
sl@0
  1343
	else
sl@0
  1344
		*(p++)=(s->version>>8),
sl@0
  1345
		*(p++)=s->version&0xff;
sl@0
  1346
sl@0
  1347
	/* field where we are to write out packet epoch, seq num and len */
sl@0
  1348
	pseq=p; 
sl@0
  1349
	p+=10;
sl@0
  1350
sl@0
  1351
	/* lets setup the record stuff. */
sl@0
  1352
sl@0
  1353
	/* Make space for the explicit IV in case of CBC.
sl@0
  1354
	 * (this is a bit of a boundary violation, but what the heck).
sl@0
  1355
	 */
sl@0
  1356
	if ( s->enc_write_ctx && 
sl@0
  1357
		(EVP_CIPHER_mode( s->enc_write_ctx->cipher ) & EVP_CIPH_CBC_MODE))
sl@0
  1358
		bs = EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
sl@0
  1359
	else
sl@0
  1360
		bs = 0;
sl@0
  1361
sl@0
  1362
	wr->data=p + bs;  /* make room for IV in case of CBC */
sl@0
  1363
	wr->length=(int)len;
sl@0
  1364
	wr->input=(unsigned char *)buf;
sl@0
  1365
sl@0
  1366
	/* we now 'read' from wr->input, wr->length bytes into
sl@0
  1367
	 * wr->data */
sl@0
  1368
sl@0
  1369
	/* first we compress */
sl@0
  1370
	if (s->compress != NULL)
sl@0
  1371
		{
sl@0
  1372
		if (!ssl3_do_compress(s))
sl@0
  1373
			{
sl@0
  1374
			SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE);
sl@0
  1375
			goto err;
sl@0
  1376
			}
sl@0
  1377
		}
sl@0
  1378
	else
sl@0
  1379
		{
sl@0
  1380
		memcpy(wr->data,wr->input,wr->length);
sl@0
  1381
		wr->input=wr->data;
sl@0
  1382
		}
sl@0
  1383
sl@0
  1384
	/* we should still have the output to wr->data and the input
sl@0
  1385
	 * from wr->input.  Length should be wr->length.
sl@0
  1386
	 * wr->data still points in the wb->buf */
sl@0
  1387
sl@0
  1388
	if (mac_size != 0)
sl@0
  1389
		{
sl@0
  1390
		s->method->ssl3_enc->mac(s,&(p[wr->length + bs]),1);
sl@0
  1391
		wr->length+=mac_size;
sl@0
  1392
		}
sl@0
  1393
sl@0
  1394
	/* this is true regardless of mac size */
sl@0
  1395
	wr->input=p;
sl@0
  1396
	wr->data=p;
sl@0
  1397
sl@0
  1398
sl@0
  1399
	/* ssl3_enc can only have an error on read */
sl@0
  1400
	if (bs)	/* bs != 0 in case of CBC */
sl@0
  1401
		{
sl@0
  1402
		RAND_pseudo_bytes(p,bs);
sl@0
  1403
		/* master IV and last CBC residue stand for
sl@0
  1404
		 * the rest of randomness */
sl@0
  1405
		wr->length += bs;
sl@0
  1406
		}
sl@0
  1407
sl@0
  1408
	s->method->ssl3_enc->enc(s,1);
sl@0
  1409
sl@0
  1410
	/* record length after mac and block padding */
sl@0
  1411
/*	if (type == SSL3_RT_APPLICATION_DATA ||
sl@0
  1412
	(type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
sl@0
  1413
	
sl@0
  1414
	/* there's only one epoch between handshake and app data */
sl@0
  1415
	
sl@0
  1416
	s2n(s->d1->w_epoch, pseq);
sl@0
  1417
sl@0
  1418
	/* XDTLS: ?? */
sl@0
  1419
/*	else
sl@0
  1420
	s2n(s->d1->handshake_epoch, pseq); */
sl@0
  1421
sl@0
  1422
	memcpy(pseq, &(s->s3->write_sequence[2]), 6);
sl@0
  1423
	pseq+=6;
sl@0
  1424
	s2n(wr->length,pseq);
sl@0
  1425
sl@0
  1426
	/* we should now have
sl@0
  1427
	 * wr->data pointing to the encrypted data, which is
sl@0
  1428
	 * wr->length long */
sl@0
  1429
	wr->type=type; /* not needed but helps for debugging */
sl@0
  1430
	wr->length+=DTLS1_RT_HEADER_LENGTH;
sl@0
  1431
sl@0
  1432
#if 0  /* this is now done at the message layer */
sl@0
  1433
	/* buffer the record, making it easy to handle retransmits */
sl@0
  1434
	if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
sl@0
  1435
		dtls1_buffer_record(s, wr->data, wr->length, 
sl@0
  1436
			*((PQ_64BIT *)&(s->s3->write_sequence[0])));
sl@0
  1437
#endif
sl@0
  1438
sl@0
  1439
	ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
sl@0
  1440
sl@0
  1441
	if (create_empty_fragment)
sl@0
  1442
		{
sl@0
  1443
		/* we are in a recursive call;
sl@0
  1444
		 * just return the length, don't write out anything here
sl@0
  1445
		 */
sl@0
  1446
		return wr->length;
sl@0
  1447
		}
sl@0
  1448
sl@0
  1449
	/* now let's set up wb */
sl@0
  1450
	wb->left = prefix_len + wr->length;
sl@0
  1451
	wb->offset = 0;
sl@0
  1452
sl@0
  1453
	/* memorize arguments so that ssl3_write_pending can detect bad write retries later */
sl@0
  1454
	s->s3->wpend_tot=len;
sl@0
  1455
	s->s3->wpend_buf=buf;
sl@0
  1456
	s->s3->wpend_type=type;
sl@0
  1457
	s->s3->wpend_ret=len;
sl@0
  1458
sl@0
  1459
	/* we now just need to write the buffer */
sl@0
  1460
	return ssl3_write_pending(s,type,buf,len);
sl@0
  1461
err:
sl@0
  1462
	return -1;
sl@0
  1463
	}
sl@0
  1464
sl@0
  1465
sl@0
  1466
sl@0
  1467
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
sl@0
  1468
	PQ_64BIT *seq_num)
sl@0
  1469
	{
sl@0
  1470
#if PQ_64BIT_IS_INTEGER
sl@0
  1471
	PQ_64BIT mask = 0x0000000000000001L;
sl@0
  1472
#endif
sl@0
  1473
	PQ_64BIT rcd_num, tmp;
sl@0
  1474
sl@0
  1475
	pq_64bit_init(&rcd_num);
sl@0
  1476
	pq_64bit_init(&tmp);
sl@0
  1477
sl@0
  1478
	/* this is the sequence number for the record just read */
sl@0
  1479
	pq_64bit_bin2num(&rcd_num, s->s3->read_sequence, 8);
sl@0
  1480
sl@0
  1481
	
sl@0
  1482
	if (pq_64bit_gt(&rcd_num, &(bitmap->max_seq_num)) ||
sl@0
  1483
		pq_64bit_eq(&rcd_num, &(bitmap->max_seq_num)))
sl@0
  1484
		{
sl@0
  1485
		pq_64bit_assign(seq_num, &rcd_num);
sl@0
  1486
		pq_64bit_free(&rcd_num);
sl@0
  1487
		pq_64bit_free(&tmp);
sl@0
  1488
		return 1;  /* this record is new */
sl@0
  1489
		}
sl@0
  1490
sl@0
  1491
	pq_64bit_sub(&tmp, &(bitmap->max_seq_num), &rcd_num);
sl@0
  1492
sl@0
  1493
	if ( pq_64bit_get_word(&tmp) > bitmap->length)
sl@0
  1494
		{
sl@0
  1495
		pq_64bit_free(&rcd_num);
sl@0
  1496
		pq_64bit_free(&tmp);
sl@0
  1497
		return 0;  /* stale, outside the window */
sl@0
  1498
		}
sl@0
  1499
sl@0
  1500
#if PQ_64BIT_IS_BIGNUM
sl@0
  1501
	{
sl@0
  1502
	int offset;
sl@0
  1503
	pq_64bit_sub(&tmp, &(bitmap->max_seq_num), &rcd_num);
sl@0
  1504
	pq_64bit_sub_word(&tmp, 1);
sl@0
  1505
	offset = pq_64bit_get_word(&tmp);
sl@0
  1506
	if ( pq_64bit_is_bit_set(&(bitmap->map), offset))
sl@0
  1507
		{
sl@0
  1508
		pq_64bit_free(&rcd_num);
sl@0
  1509
		pq_64bit_free(&tmp);
sl@0
  1510
		return 0;
sl@0
  1511
		}
sl@0
  1512
	}
sl@0
  1513
#else
sl@0
  1514
	mask <<= (bitmap->max_seq_num - rcd_num - 1);
sl@0
  1515
	if (bitmap->map & mask)
sl@0
  1516
		return 0; /* record previously received */
sl@0
  1517
#endif
sl@0
  1518
	
sl@0
  1519
	pq_64bit_assign(seq_num, &rcd_num);
sl@0
  1520
	pq_64bit_free(&rcd_num);
sl@0
  1521
	pq_64bit_free(&tmp);
sl@0
  1522
	return 1;
sl@0
  1523
	}
sl@0
  1524
sl@0
  1525
sl@0
  1526
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
sl@0
  1527
	{
sl@0
  1528
	unsigned int shift;
sl@0
  1529
	PQ_64BIT rcd_num;
sl@0
  1530
	PQ_64BIT tmp;
sl@0
  1531
	PQ_64BIT_CTX *ctx;
sl@0
  1532
sl@0
  1533
	pq_64bit_init(&rcd_num);
sl@0
  1534
	pq_64bit_init(&tmp);
sl@0
  1535
sl@0
  1536
	pq_64bit_bin2num(&rcd_num, s->s3->read_sequence, 8);
sl@0
  1537
sl@0
  1538
	/* unfortunate code complexity due to 64-bit manipulation support
sl@0
  1539
	 * on 32-bit machines */
sl@0
  1540
	if ( pq_64bit_gt(&rcd_num, &(bitmap->max_seq_num)) ||
sl@0
  1541
		pq_64bit_eq(&rcd_num, &(bitmap->max_seq_num)))
sl@0
  1542
		{
sl@0
  1543
		pq_64bit_sub(&tmp, &rcd_num, &(bitmap->max_seq_num));
sl@0
  1544
		pq_64bit_add_word(&tmp, 1);
sl@0
  1545
sl@0
  1546
		shift = (unsigned int)pq_64bit_get_word(&tmp);
sl@0
  1547
sl@0
  1548
		pq_64bit_lshift(&(tmp), &(bitmap->map), shift);
sl@0
  1549
		pq_64bit_assign(&(bitmap->map), &tmp);
sl@0
  1550
sl@0
  1551
		pq_64bit_set_bit(&(bitmap->map), 0);
sl@0
  1552
		pq_64bit_add_word(&rcd_num, 1);
sl@0
  1553
		pq_64bit_assign(&(bitmap->max_seq_num), &rcd_num);
sl@0
  1554
sl@0
  1555
		pq_64bit_assign_word(&tmp, 1);
sl@0
  1556
		pq_64bit_lshift(&tmp, &tmp, bitmap->length);
sl@0
  1557
		ctx = pq_64bit_ctx_new(&ctx);
sl@0
  1558
		pq_64bit_mod(&(bitmap->map), &(bitmap->map), &tmp, ctx);
sl@0
  1559
		pq_64bit_ctx_free(ctx);
sl@0
  1560
		}
sl@0
  1561
	else
sl@0
  1562
		{
sl@0
  1563
		pq_64bit_sub(&tmp, &(bitmap->max_seq_num), &rcd_num);
sl@0
  1564
		pq_64bit_sub_word(&tmp, 1);
sl@0
  1565
		shift = (unsigned int)pq_64bit_get_word(&tmp);
sl@0
  1566
sl@0
  1567
		pq_64bit_set_bit(&(bitmap->map), shift);
sl@0
  1568
		}
sl@0
  1569
sl@0
  1570
	pq_64bit_free(&rcd_num);
sl@0
  1571
	pq_64bit_free(&tmp);
sl@0
  1572
	}
sl@0
  1573
sl@0
  1574
sl@0
  1575
int dtls1_dispatch_alert(SSL *s)
sl@0
  1576
	{
sl@0
  1577
	int i,j;
sl@0
  1578
	void (*cb)(const SSL *ssl,int type,int val)=NULL;
sl@0
  1579
	unsigned char buf[2 + 2 + 3]; /* alert level + alert desc + message seq +frag_off */
sl@0
  1580
	unsigned char *ptr = &buf[0];
sl@0
  1581
sl@0
  1582
	s->s3->alert_dispatch=0;
sl@0
  1583
sl@0
  1584
	memset(buf, 0x00, sizeof(buf));
sl@0
  1585
	*ptr++ = s->s3->send_alert[0];
sl@0
  1586
	*ptr++ = s->s3->send_alert[1];
sl@0
  1587
sl@0
  1588
	if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
sl@0
  1589
		{	
sl@0
  1590
		s2n(s->d1->handshake_read_seq, ptr);
sl@0
  1591
#if 0
sl@0
  1592
		if ( s->d1->r_msg_hdr.frag_off == 0)  /* waiting for a new msg */
sl@0
  1593
sl@0
  1594
		else
sl@0
  1595
			s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
sl@0
  1596
#endif
sl@0
  1597
sl@0
  1598
#if 0
sl@0
  1599
		fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
sl@0
  1600
#endif
sl@0
  1601
		l2n3(s->d1->r_msg_hdr.frag_off, ptr);
sl@0
  1602
		}
sl@0
  1603
sl@0
  1604
	i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
sl@0
  1605
	if (i <= 0)
sl@0
  1606
		{
sl@0
  1607
		s->s3->alert_dispatch=1;
sl@0
  1608
		/* fprintf( stderr, "not done with alert\n" ); */
sl@0
  1609
		}
sl@0
  1610
	else
sl@0
  1611
		{
sl@0
  1612
		if ( s->s3->send_alert[0] == SSL3_AL_FATAL ||
sl@0
  1613
			s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
sl@0
  1614
			(void)BIO_flush(s->wbio);
sl@0
  1615
sl@0
  1616
		if (s->msg_callback)
sl@0
  1617
			s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 
sl@0
  1618
				2, s, s->msg_callback_arg);
sl@0
  1619
sl@0
  1620
		if (s->info_callback != NULL)
sl@0
  1621
			cb=s->info_callback;
sl@0
  1622
		else if (s->ctx->info_callback != NULL)
sl@0
  1623
			cb=s->ctx->info_callback;
sl@0
  1624
sl@0
  1625
		if (cb != NULL)
sl@0
  1626
			{
sl@0
  1627
			j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
sl@0
  1628
			cb(s,SSL_CB_WRITE_ALERT,j);
sl@0
  1629
			}
sl@0
  1630
		}
sl@0
  1631
	return(i);
sl@0
  1632
	}
sl@0
  1633
sl@0
  1634
sl@0
  1635
static DTLS1_BITMAP *
sl@0
  1636
dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
sl@0
  1637
    {
sl@0
  1638
    
sl@0
  1639
    *is_next_epoch = 0;
sl@0
  1640
sl@0
  1641
    /* In current epoch, accept HM, CCS, DATA, & ALERT */
sl@0
  1642
    if (rr->epoch == s->d1->r_epoch)
sl@0
  1643
        return &s->d1->bitmap;
sl@0
  1644
sl@0
  1645
    /* Only HM and ALERT messages can be from the next epoch */
sl@0
  1646
    else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
sl@0
  1647
        (rr->type == SSL3_RT_HANDSHAKE ||
sl@0
  1648
            rr->type == SSL3_RT_ALERT))
sl@0
  1649
        {
sl@0
  1650
        *is_next_epoch = 1;
sl@0
  1651
        return &s->d1->next_bitmap;
sl@0
  1652
        }
sl@0
  1653
sl@0
  1654
    return NULL;
sl@0
  1655
    }
sl@0
  1656
sl@0
  1657
#if 0
sl@0
  1658
static int
sl@0
  1659
dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
sl@0
  1660
	unsigned long *offset)
sl@0
  1661
	{
sl@0
  1662
sl@0
  1663
	/* alerts are passed up immediately */
sl@0
  1664
	if ( rr->type == SSL3_RT_APPLICATION_DATA ||
sl@0
  1665
		rr->type == SSL3_RT_ALERT)
sl@0
  1666
		return 0;
sl@0
  1667
sl@0
  1668
	/* Only need to buffer if a handshake is underway.
sl@0
  1669
	 * (this implies that Hello Request and Client Hello are passed up
sl@0
  1670
	 * immediately) */
sl@0
  1671
	if ( SSL_in_init(s))
sl@0
  1672
		{
sl@0
  1673
		unsigned char *data = rr->data;
sl@0
  1674
		/* need to extract the HM/CCS sequence number here */
sl@0
  1675
		if ( rr->type == SSL3_RT_HANDSHAKE ||
sl@0
  1676
			rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
sl@0
  1677
			{
sl@0
  1678
			unsigned short seq_num;
sl@0
  1679
			struct hm_header_st msg_hdr;
sl@0
  1680
			struct ccs_header_st ccs_hdr;
sl@0
  1681
sl@0
  1682
			if ( rr->type == SSL3_RT_HANDSHAKE)
sl@0
  1683
				{
sl@0
  1684
				dtls1_get_message_header(data, &msg_hdr);
sl@0
  1685
				seq_num = msg_hdr.seq;
sl@0
  1686
				*offset = msg_hdr.frag_off;
sl@0
  1687
				}
sl@0
  1688
			else
sl@0
  1689
				{
sl@0
  1690
				dtls1_get_ccs_header(data, &ccs_hdr);
sl@0
  1691
				seq_num = ccs_hdr.seq;
sl@0
  1692
				*offset = 0;
sl@0
  1693
				}
sl@0
  1694
				
sl@0
  1695
			/* this is either a record we're waiting for, or a
sl@0
  1696
			 * retransmit of something we happened to previously 
sl@0
  1697
			 * receive (higher layers will drop the repeat silently */
sl@0
  1698
			if ( seq_num < s->d1->handshake_read_seq)
sl@0
  1699
				return 0;
sl@0
  1700
			if (rr->type == SSL3_RT_HANDSHAKE && 
sl@0
  1701
				seq_num == s->d1->handshake_read_seq &&
sl@0
  1702
				msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
sl@0
  1703
				return 0;
sl@0
  1704
			else if ( seq_num == s->d1->handshake_read_seq &&
sl@0
  1705
				(rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
sl@0
  1706
					msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
sl@0
  1707
				return 0;
sl@0
  1708
			else
sl@0
  1709
				{
sl@0
  1710
				*priority = seq_num;
sl@0
  1711
				return 1;
sl@0
  1712
				}
sl@0
  1713
			}
sl@0
  1714
		else /* unknown record type */
sl@0
  1715
			return 0;
sl@0
  1716
		}
sl@0
  1717
sl@0
  1718
	return 0;
sl@0
  1719
	}
sl@0
  1720
#endif
sl@0
  1721
sl@0
  1722
void
sl@0
  1723
dtls1_reset_seq_numbers(SSL *s, int rw)
sl@0
  1724
	{
sl@0
  1725
	unsigned char *seq;
sl@0
  1726
	unsigned int seq_bytes = sizeof(s->s3->read_sequence);
sl@0
  1727
sl@0
  1728
	if ( rw & SSL3_CC_READ)
sl@0
  1729
		{
sl@0
  1730
		seq = s->s3->read_sequence;
sl@0
  1731
		s->d1->r_epoch++;
sl@0
  1732
sl@0
  1733
		pq_64bit_assign(&(s->d1->bitmap.map), &(s->d1->next_bitmap.map));
sl@0
  1734
		s->d1->bitmap.length = s->d1->next_bitmap.length;
sl@0
  1735
		pq_64bit_assign(&(s->d1->bitmap.max_seq_num), 
sl@0
  1736
			&(s->d1->next_bitmap.max_seq_num));
sl@0
  1737
sl@0
  1738
		pq_64bit_free(&(s->d1->next_bitmap.map));
sl@0
  1739
		pq_64bit_free(&(s->d1->next_bitmap.max_seq_num));
sl@0
  1740
		memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
sl@0
  1741
		pq_64bit_init(&(s->d1->next_bitmap.map));
sl@0
  1742
		pq_64bit_init(&(s->d1->next_bitmap.max_seq_num));
sl@0
  1743
		}
sl@0
  1744
	else
sl@0
  1745
		{
sl@0
  1746
		seq = s->s3->write_sequence;
sl@0
  1747
		s->d1->w_epoch++;
sl@0
  1748
		}
sl@0
  1749
sl@0
  1750
	memset(seq, 0x00, seq_bytes);
sl@0
  1751
	}
sl@0
  1752
sl@0
  1753
#if PQ_64BIT_IS_INTEGER
sl@0
  1754
static PQ_64BIT
sl@0
  1755
bytes_to_long_long(unsigned char *bytes, PQ_64BIT *num)
sl@0
  1756
       {
sl@0
  1757
       PQ_64BIT _num;
sl@0
  1758
sl@0
  1759
       _num = (((PQ_64BIT)bytes[0]) << 56) |
sl@0
  1760
               (((PQ_64BIT)bytes[1]) << 48) |
sl@0
  1761
               (((PQ_64BIT)bytes[2]) << 40) |
sl@0
  1762
               (((PQ_64BIT)bytes[3]) << 32) |
sl@0
  1763
               (((PQ_64BIT)bytes[4]) << 24) |
sl@0
  1764
               (((PQ_64BIT)bytes[5]) << 16) |
sl@0
  1765
               (((PQ_64BIT)bytes[6]) <<  8) |
sl@0
  1766
               (((PQ_64BIT)bytes[7])      );
sl@0
  1767
sl@0
  1768
	   *num = _num ;
sl@0
  1769
       return _num;
sl@0
  1770
       }
sl@0
  1771
#endif
sl@0
  1772
sl@0
  1773
sl@0
  1774
static void
sl@0
  1775
dtls1_clear_timeouts(SSL *s)
sl@0
  1776
	{
sl@0
  1777
	memset(&(s->d1->timeout), 0x00, sizeof(struct dtls1_timeout_st));
sl@0
  1778
	}