]> git.ipfire.org Git - thirdparty/openssl.git/blob - ssl/record/rec_layer_d1.c
Remove some unnecessary function pointers from OSSL_RECORD_METHOD
[thirdparty/openssl.git] / ssl / record / rec_layer_d1.c
1 /*
2 * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <stdio.h>
11 #include <errno.h>
12 #include "../ssl_local.h"
13 #include <openssl/evp.h>
14 #include <openssl/buffer.h>
15 #include "record_local.h"
16 #include "internal/packet.h"
17 #include "internal/cryptlib.h"
18
19 int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
20 {
21 DTLS_RECORD_LAYER *d;
22
23 if ((d = OPENSSL_malloc(sizeof(*d))) == NULL) {
24 ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
25 return 0;
26 }
27
28 rl->d = d;
29
30 d->buffered_app_data.q = pqueue_new();
31
32 if (d->buffered_app_data.q == NULL) {
33 OPENSSL_free(d);
34 rl->d = NULL;
35 return 0;
36 }
37
38 return 1;
39 }
40
41 void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
42 {
43 if (rl->d == NULL)
44 return;
45
46 DTLS_RECORD_LAYER_clear(rl);
47 pqueue_free(rl->d->buffered_app_data.q);
48 OPENSSL_free(rl->d);
49 rl->d = NULL;
50 }
51
52 void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
53 {
54 DTLS_RECORD_LAYER *d;
55 pitem *item = NULL;
56 TLS_RECORD *rec;
57 pqueue *buffered_app_data;
58
59 d = rl->d;
60
61 while ((item = pqueue_pop(d->buffered_app_data.q)) != NULL) {
62 rec = (TLS_RECORD *)item->data;
63 if (rl->s->options & SSL_OP_CLEANSE_PLAINTEXT)
64 OPENSSL_cleanse(rec->data, rec->length);
65 OPENSSL_free(rec->data);
66 OPENSSL_free(item->data);
67 pitem_free(item);
68 }
69
70 buffered_app_data = d->buffered_app_data.q;
71 memset(d, 0, sizeof(*d));
72 d->buffered_app_data.q = buffered_app_data;
73 }
74
75 void DTLS_RECORD_LAYER_set_saved_w_epoch(RECORD_LAYER *rl, unsigned short e)
76 {
77 if (e == rl->d->w_epoch - 1) {
78 memcpy(rl->d->curr_write_sequence,
79 rl->write_sequence, sizeof(rl->write_sequence));
80 memcpy(rl->write_sequence,
81 rl->d->last_write_sequence, sizeof(rl->write_sequence));
82 } else if (e == rl->d->w_epoch + 1) {
83 memcpy(rl->d->last_write_sequence,
84 rl->write_sequence, sizeof(unsigned char[8]));
85 memcpy(rl->write_sequence,
86 rl->d->curr_write_sequence, sizeof(rl->write_sequence));
87 }
88 rl->d->w_epoch = e;
89 }
90
91 void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq)
92 {
93 memcpy(rl->write_sequence, seq, SEQ_NUM_SIZE);
94 }
95
96 int dtls_buffer_record(SSL_CONNECTION *s, TLS_RECORD *rec)
97 {
98 TLS_RECORD *rdata;
99 pitem *item;
100 record_pqueue *queue = &(s->rlayer.d->buffered_app_data);
101
102 /* Limit the size of the queue to prevent DOS attacks */
103 if (pqueue_size(queue->q) >= 100)
104 return 0;
105
106 /* We don't buffer partially read records */
107 if (!ossl_assert(rec->off == 0))
108 return -1;
109
110 rdata = OPENSSL_malloc(sizeof(*rdata));
111 item = pitem_new(rec->seq_num, rdata);
112 if (rdata == NULL || item == NULL) {
113 OPENSSL_free(rdata);
114 pitem_free(item);
115 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
116 return -1;
117 }
118
119 *rdata = *rec;
120 /*
121 * We will release the record from the record layer soon, so we take a copy
122 * now. Copying data isn't good - but this should be infrequent so we
123 * accept it here.
124 */
125 rdata->data = OPENSSL_memdup(rec->data, rec->length);
126 if (rdata->data == NULL) {
127 OPENSSL_free(rdata);
128 pitem_free(item);
129 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
130 return -1;
131 }
132 /*
133 * We use a NULL rechandle to indicate that the data field has been
134 * allocated by us.
135 */
136 rdata->rechandle = NULL;
137
138 item->data = rdata;
139
140 #ifndef OPENSSL_NO_SCTP
141 /* Store bio_dgram_sctp_rcvinfo struct */
142 if (BIO_dgram_is_sctp(SSL_get_rbio(ssl)) &&
143 (SSL_get_state(ssl) == TLS_ST_SR_FINISHED
144 || SSL_get_state(ssl) == TLS_ST_CR_FINISHED)) {
145 BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
146 sizeof(rdata->recordinfo), &rdata->recordinfo);
147 }
148 #endif
149
150 if (pqueue_insert(queue->q, item) == NULL) {
151 /* Must be a duplicate so ignore it */
152 OPENSSL_free(rdata->data);
153 OPENSSL_free(rdata);
154 pitem_free(item);
155 }
156
157 return 1;
158 }
159
160 /* Unbuffer a previously buffered TLS_RECORD structure if any */
161 static void dtls_unbuffer_record(SSL_CONNECTION *s)
162 {
163 TLS_RECORD *rdata;
164 pitem *item;
165
166 /* If we already have records to handle then do nothing */
167 if (s->rlayer.curr_rec < s->rlayer.num_recs)
168 return;
169
170 item = pqueue_pop(s->rlayer.d->buffered_app_data.q);
171 if (item != NULL) {
172 rdata = (TLS_RECORD *)item->data;
173
174 s->rlayer.tlsrecs[0] = *rdata;
175 s->rlayer.num_recs = 1;
176 s->rlayer.curr_rec = 0;
177
178 #ifndef OPENSSL_NO_SCTP
179 /* Restore bio_dgram_sctp_rcvinfo struct */
180 if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
181 DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
182 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
183 sizeof(rdata->recordinfo), &rdata->recordinfo);
184 }
185 #endif
186
187 /* Set proper sequence number for mac calculation */
188 memcpy(&(s->rlayer.read_sequence[2]), &(rdata->seq_num[2]), 6);
189
190 OPENSSL_free(item->data);
191 pitem_free(item);
192 }
193 }
194
195 /*-
196 * Return up to 'len' payload bytes received in 'type' records.
197 * 'type' is one of the following:
198 *
199 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
200 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
201 * - 0 (during a shutdown, no data has to be returned)
202 *
203 * If we don't have stored data to work from, read a SSL/TLS record first
204 * (possibly multiple records if we still don't have anything to return).
205 *
206 * This function must handle any surprises the peer may have for us, such as
207 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
208 * messages are treated as if they were handshake messages *if* the |recd_type|
209 * argument is non NULL.
210 * Also if record payloads contain fragments too small to process, we store
211 * them until there is enough for the respective protocol (the record protocol
212 * may use arbitrary fragmentation and even interleaving):
213 * Change cipher spec protocol
214 * just 1 byte needed, no need for keeping anything stored
215 * Alert protocol
216 * 2 bytes needed (AlertLevel, AlertDescription)
217 * Handshake protocol
218 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
219 * to detect unexpected Client Hello and Hello Request messages
220 * here, anything else is handled by higher layers
221 * Application data protocol
222 * none of our business
223 */
224 int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
225 size_t len, int peek, size_t *readbytes)
226 {
227 int i, j, ret;
228 size_t n;
229 TLS_RECORD *rr;
230 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
231 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
232
233 if (sc == NULL)
234 return -1;
235
236 if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
237 (type != SSL3_RT_HANDSHAKE)) ||
238 (peek && (type != SSL3_RT_APPLICATION_DATA))) {
239 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
240 return -1;
241 }
242
243 if (!ossl_statem_get_in_handshake(sc) && SSL_in_init(s)) {
244 /* type == SSL3_RT_APPLICATION_DATA */
245 i = sc->handshake_func(s);
246 /* SSLfatal() already called if appropriate */
247 if (i < 0)
248 return i;
249 if (i == 0)
250 return -1;
251 }
252
253 start:
254 sc->rwstate = SSL_NOTHING;
255
256 /*
257 * We are not handshaking and have no data yet, so process data buffered
258 * during the last handshake in advance, if any.
259 */
260 if (SSL_is_init_finished(s))
261 dtls_unbuffer_record(sc);
262
263 /* Check for timeout */
264 if (dtls1_handle_timeout(sc) > 0) {
265 goto start;
266 } else if (ossl_statem_in_error(sc)) {
267 /* dtls1_handle_timeout() has failed with a fatal error */
268 return -1;
269 }
270
271 /* get new packet if necessary */
272 if (sc->rlayer.curr_rec >= sc->rlayer.num_recs) {
273 sc->rlayer.curr_rec = sc->rlayer.num_recs = 0;
274 do {
275 rr = &sc->rlayer.tlsrecs[sc->rlayer.num_recs];
276
277 /* TODO(RECLAYER): Check HANDLE_RLAYER_RETURN for DTLS */
278 ret = HANDLE_RLAYER_RETURN(sc,
279 sc->rrlmethod->read_record(sc->rrl, &rr->rechandle,
280 &rr->version, &rr->type,
281 &rr->data, &rr->length,
282 &rr->epoch, rr->seq_num));
283 if (ret <= 0) {
284 ret = dtls1_read_failed(sc, ret);
285 /*
286 * Anything other than a timeout is an error. SSLfatal() already
287 * called if appropriate.
288 */
289 if (ret <= 0)
290 return ret;
291 else
292 goto start;
293 }
294 rr->off = 0;
295 sc->rlayer.num_recs++;
296 } while (sc->rrlmethod->processed_read_pending(sc->rrl)
297 && sc->rlayer.num_recs < SSL_MAX_PIPELINES);
298 }
299 rr = &sc->rlayer.tlsrecs[sc->rlayer.curr_rec];
300
301 /*
302 * Reset the count of consecutive warning alerts if we've got a non-empty
303 * record that isn't an alert.
304 */
305 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
306 sc->rlayer.alert_count = 0;
307
308 /* we now have a packet which can be read and processed */
309
310 if (sc->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
311 * reset by ssl3_get_finished */
312 && (rr->type != SSL3_RT_HANDSHAKE)) {
313 /*
314 * We now have application data between CCS and Finished. Most likely
315 * the packets were reordered on their way, so buffer the application
316 * data for later processing rather than dropping the connection.
317 */
318 if (dtls_buffer_record(sc, rr) < 0) {
319 /* SSLfatal() already called */
320 return -1;
321 }
322 ssl_release_record(sc, rr);
323 goto start;
324 }
325
326 /*
327 * If the other end has shut down, throw anything we read away (even in
328 * 'peek' mode)
329 */
330 if (sc->shutdown & SSL_RECEIVED_SHUTDOWN) {
331 ssl_release_record(sc, rr);
332 sc->rwstate = SSL_NOTHING;
333 return 0;
334 }
335
336 if (type == rr->type
337 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
338 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
339 /*
340 * SSL3_RT_APPLICATION_DATA or
341 * SSL3_RT_HANDSHAKE or
342 * SSL3_RT_CHANGE_CIPHER_SPEC
343 */
344 /*
345 * make sure that we are not getting application data when we are
346 * doing a handshake for the first time
347 */
348 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
349 (sc->enc_read_ctx == NULL)) {
350 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
351 SSL_R_APP_DATA_IN_HANDSHAKE);
352 return -1;
353 }
354
355 if (recvd_type != NULL)
356 *recvd_type = rr->type;
357
358 if (len == 0) {
359 /*
360 * Release a zero length record. This ensures multiple calls to
361 * SSL_read() with a zero length buffer will eventually cause
362 * SSL_pending() to report data as being available.
363 */
364 if (rr->length == 0)
365 ssl_release_record(sc, rr);
366 return 0;
367 }
368
369 if (len > rr->length)
370 n = rr->length;
371 else
372 n = len;
373
374 memcpy(buf, &(rr->data[rr->off]), n);
375 if (peek) {
376 if (rr->length == 0)
377 ssl_release_record(sc, rr);
378 } else {
379 if (sc->options & SSL_OP_CLEANSE_PLAINTEXT)
380 OPENSSL_cleanse(&(rr->data[rr->off]), n);
381 rr->length -= n;
382 rr->off += n;
383 if (rr->length == 0) {
384 /* TODO(RECLAYER): Do something with this? */
385 sc->rlayer.rstate = SSL_ST_READ_HEADER;
386 ssl_release_record(sc, rr);
387 }
388 }
389 #ifndef OPENSSL_NO_SCTP
390 /*
391 * We might had to delay a close_notify alert because of reordered
392 * app data. If there was an alert and there is no message to read
393 * anymore, finally set shutdown.
394 */
395 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
396 sc->d1->shutdown_received
397 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) <= 0) {
398 sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
399 return 0;
400 }
401 #endif
402 *readbytes = n;
403 return 1;
404 }
405
406 /*
407 * If we get here, then type != rr->type; if we have a handshake message,
408 * then it was unexpected (Hello Request or Client Hello).
409 */
410
411 if (rr->type == SSL3_RT_ALERT) {
412 unsigned int alert_level, alert_descr;
413 unsigned char *alert_bytes = rr->data + rr->off;
414 PACKET alert;
415
416 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
417 || !PACKET_get_1(&alert, &alert_level)
418 || !PACKET_get_1(&alert, &alert_descr)
419 || PACKET_remaining(&alert) != 0) {
420 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
421 return -1;
422 }
423
424 if (sc->msg_callback)
425 sc->msg_callback(0, sc->version, SSL3_RT_ALERT, alert_bytes, 2, s,
426 sc->msg_callback_arg);
427
428 if (sc->info_callback != NULL)
429 cb = sc->info_callback;
430 else if (s->ctx->info_callback != NULL)
431 cb = s->ctx->info_callback;
432
433 if (cb != NULL) {
434 j = (alert_level << 8) | alert_descr;
435 cb(s, SSL_CB_READ_ALERT, j);
436 }
437
438 if (alert_level == SSL3_AL_WARNING) {
439 sc->s3.warn_alert = alert_descr;
440 ssl_release_record(sc, rr);
441
442 sc->rlayer.alert_count++;
443 if (sc->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
444 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
445 SSL_R_TOO_MANY_WARN_ALERTS);
446 return -1;
447 }
448
449 if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
450 #ifndef OPENSSL_NO_SCTP
451 /*
452 * With SCTP and streams the socket may deliver app data
453 * after a close_notify alert. We have to check this first so
454 * that nothing gets discarded.
455 */
456 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
457 BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) > 0) {
458 sc->d1->shutdown_received = 1;
459 sc->rwstate = SSL_READING;
460 BIO_clear_retry_flags(SSL_get_rbio(s));
461 BIO_set_retry_read(SSL_get_rbio(s));
462 return -1;
463 }
464 #endif
465 sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
466 return 0;
467 }
468 } else if (alert_level == SSL3_AL_FATAL) {
469 sc->rwstate = SSL_NOTHING;
470 sc->s3.fatal_alert = alert_descr;
471 SSLfatal_data(sc, SSL_AD_NO_ALERT,
472 SSL_AD_REASON_OFFSET + alert_descr,
473 "SSL alert number %d", alert_descr);
474 sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
475 ssl_release_record(sc, rr);
476 SSL_CTX_remove_session(sc->session_ctx, sc->session);
477 return 0;
478 } else {
479 SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
480 return -1;
481 }
482
483 goto start;
484 }
485
486 if (sc->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
487 * shutdown */
488 sc->rwstate = SSL_NOTHING;
489 ssl_release_record(sc, rr);
490 return 0;
491 }
492
493 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
494 /*
495 * We can't process a CCS now, because previous handshake messages
496 * are still missing, so just drop it.
497 */
498 ssl_release_record(sc, rr);
499 goto start;
500 }
501
502 /*
503 * Unexpected handshake message (Client Hello, or protocol violation)
504 */
505 if (rr->type == SSL3_RT_HANDSHAKE && !ossl_statem_get_in_handshake(sc)) {
506 struct hm_header_st msg_hdr;
507
508 /*
509 * This may just be a stale retransmit. Also sanity check that we have
510 * at least enough record bytes for a message header
511 */
512 if (rr->epoch != sc->rlayer.d->r_epoch
513 || rr->length < DTLS1_HM_HEADER_LENGTH) {
514 ssl_release_record(sc, rr);
515 goto start;
516 }
517
518 dtls1_get_message_header(rr->data, &msg_hdr);
519
520 /*
521 * If we are server, we may have a repeated FINISHED of the client
522 * here, then retransmit our CCS and FINISHED.
523 */
524 if (msg_hdr.type == SSL3_MT_FINISHED) {
525 if (dtls1_check_timeout_num(sc) < 0) {
526 /* SSLfatal) already called */
527 return -1;
528 }
529
530 if (dtls1_retransmit_buffered_messages(sc) <= 0) {
531 /* Fail if we encountered a fatal error */
532 if (ossl_statem_in_error(sc))
533 return -1;
534 }
535 ssl_release_record(sc, rr);
536 if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
537 if (!sc->rrlmethod->unprocessed_read_pending(sc->rrl)) {
538 /* no read-ahead left? */
539 BIO *bio;
540
541 sc->rwstate = SSL_READING;
542 bio = SSL_get_rbio(s);
543 BIO_clear_retry_flags(bio);
544 BIO_set_retry_read(bio);
545 return -1;
546 }
547 }
548 goto start;
549 }
550
551 /*
552 * To get here we must be trying to read app data but found handshake
553 * data. But if we're trying to read app data, and we're not in init
554 * (which is tested for at the top of this function) then init must be
555 * finished
556 */
557 if (!ossl_assert(SSL_is_init_finished(s))) {
558 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
559 return -1;
560 }
561
562 /* We found handshake data, so we're going back into init */
563 ossl_statem_set_in_init(sc, 1);
564
565 i = sc->handshake_func(s);
566 /* SSLfatal() called if appropriate */
567 if (i < 0)
568 return i;
569 if (i == 0)
570 return -1;
571
572 if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
573 if (!sc->rrlmethod->unprocessed_read_pending(sc->rrl)) {
574 /* no read-ahead left? */
575 BIO *bio;
576 /*
577 * In the case where we try to read application data, but we
578 * trigger an SSL handshake, we return -1 with the retry
579 * option set. Otherwise renegotiation may cause nasty
580 * problems in the blocking world
581 */
582 sc->rwstate = SSL_READING;
583 bio = SSL_get_rbio(s);
584 BIO_clear_retry_flags(bio);
585 BIO_set_retry_read(bio);
586 return -1;
587 }
588 }
589 goto start;
590 }
591
592 switch (rr->type) {
593 default:
594 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
595 return -1;
596 case SSL3_RT_CHANGE_CIPHER_SPEC:
597 case SSL3_RT_ALERT:
598 case SSL3_RT_HANDSHAKE:
599 /*
600 * we already handled all of these, with the possible exception of
601 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
602 * that should not happen when type != rr->type
603 */
604 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
605 return -1;
606 case SSL3_RT_APPLICATION_DATA:
607 /*
608 * At this point, we were expecting handshake data, but have
609 * application data. If the library was running inside ssl3_read()
610 * (i.e. in_read_app_data is set) and it makes sense to read
611 * application data at this point (session renegotiation not yet
612 * started), we will indulge it.
613 */
614 if (sc->s3.in_read_app_data &&
615 (sc->s3.total_renegotiations != 0) &&
616 ossl_statem_app_data_allowed(sc)) {
617 sc->s3.in_read_app_data = 2;
618 return -1;
619 } else {
620 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
621 return -1;
622 }
623 }
624 /* not reached */
625 }
626
627 /*
628 * Call this to write data in records of type 'type' It will return <= 0 if
629 * not all data has been sent or non-blocking IO.
630 */
631 int dtls1_write_bytes(SSL_CONNECTION *s, int type, const void *buf,
632 size_t len, size_t *written)
633 {
634 int i;
635
636 if (!ossl_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH)) {
637 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
638 return -1;
639 }
640 s->rwstate = SSL_NOTHING;
641 i = do_dtls1_write(s, type, buf, len, 0, written);
642 return i;
643 }
644
645 int do_dtls1_write(SSL_CONNECTION *sc, int type, const unsigned char *buf,
646 size_t len, int create_empty_fragment, size_t *written)
647 {
648 unsigned char *p, *pseq;
649 int i, mac_size, clear = 0;
650 size_t prefix_len = 0;
651 int eivlen;
652 SSL3_RECORD wr;
653 SSL3_BUFFER *wb;
654 SSL_SESSION *sess;
655 SSL *s = SSL_CONNECTION_GET_SSL(sc);
656
657 wb = &sc->rlayer.wbuf[0];
658
659 /*
660 * DTLS writes whole datagrams, so there can't be anything left in
661 * the buffer.
662 */
663 if (!ossl_assert(SSL3_BUFFER_get_left(wb) == 0)) {
664 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
665 return 0;
666 }
667
668 /* If we have an alert to send, lets send it */
669 if (sc->s3.alert_dispatch) {
670 i = s->method->ssl_dispatch_alert(s);
671 if (i <= 0)
672 return i;
673 /* if it went, fall through and send more stuff */
674 }
675
676 if (len == 0 && !create_empty_fragment)
677 return 0;
678
679 if (len > ssl_get_max_send_fragment(sc)) {
680 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
681 return 0;
682 }
683
684 sess = sc->session;
685
686 if ((sess == NULL)
687 || (sc->enc_write_ctx == NULL)
688 || (EVP_MD_CTX_get0_md(sc->write_hash) == NULL))
689 clear = 1;
690
691 if (clear)
692 mac_size = 0;
693 else {
694 mac_size = EVP_MD_CTX_get_size(sc->write_hash);
695 if (mac_size < 0) {
696 SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
697 SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
698 return -1;
699 }
700 }
701
702 p = SSL3_BUFFER_get_buf(wb) + prefix_len;
703
704 /* write the header */
705
706 *(p++) = type & 0xff;
707 SSL3_RECORD_set_type(&wr, type);
708 /*
709 * Special case: for hello verify request, client version 1.0 and we
710 * haven't decided which version to use yet send back using version 1.0
711 * header: otherwise some clients will ignore it.
712 */
713 if (s->method->version == DTLS_ANY_VERSION &&
714 sc->max_proto_version != DTLS1_BAD_VER) {
715 *(p++) = DTLS1_VERSION >> 8;
716 *(p++) = DTLS1_VERSION & 0xff;
717 } else {
718 *(p++) = sc->version >> 8;
719 *(p++) = sc->version & 0xff;
720 }
721
722 /* field where we are to write out packet epoch, seq num and len */
723 pseq = p;
724 p += 10;
725
726 /* Explicit IV length, block ciphers appropriate version flag */
727 if (sc->enc_write_ctx) {
728 int mode = EVP_CIPHER_CTX_get_mode(sc->enc_write_ctx);
729 if (mode == EVP_CIPH_CBC_MODE) {
730 eivlen = EVP_CIPHER_CTX_get_iv_length(sc->enc_write_ctx);
731 if (eivlen < 0) {
732 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
733 return -1;
734 }
735 if (eivlen <= 1)
736 eivlen = 0;
737 }
738 /* Need explicit part of IV for GCM mode */
739 else if (mode == EVP_CIPH_GCM_MODE)
740 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
741 else if (mode == EVP_CIPH_CCM_MODE)
742 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
743 else
744 eivlen = 0;
745 } else
746 eivlen = 0;
747
748 /* lets setup the record stuff. */
749 SSL3_RECORD_set_data(&wr, p + eivlen); /* make room for IV in case of CBC */
750 SSL3_RECORD_set_length(&wr, len);
751 SSL3_RECORD_set_input(&wr, (unsigned char *)buf);
752
753 /*
754 * we now 'read' from wr.input, wr.length bytes into wr.data
755 */
756
757 /* first we compress */
758 if (sc->compress != NULL) {
759 if (!ssl3_do_compress(sc, &wr)) {
760 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
761 return -1;
762 }
763 } else {
764 memcpy(SSL3_RECORD_get_data(&wr), SSL3_RECORD_get_input(&wr),
765 SSL3_RECORD_get_length(&wr));
766 SSL3_RECORD_reset_input(&wr);
767 }
768
769 /*
770 * we should still have the output to wr.data and the input from
771 * wr.input. Length should be wr.length. wr.data still points in the
772 * wb->buf
773 */
774
775 if (!SSL_WRITE_ETM(sc) && mac_size != 0) {
776 if (!s->method->ssl3_enc->mac(sc, &wr,
777 &(p[SSL3_RECORD_get_length(&wr) + eivlen]),
778 1)) {
779 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
780 return -1;
781 }
782 SSL3_RECORD_add_length(&wr, mac_size);
783 }
784
785 /* this is true regardless of mac size */
786 SSL3_RECORD_set_data(&wr, p);
787 SSL3_RECORD_reset_input(&wr);
788
789 if (eivlen)
790 SSL3_RECORD_add_length(&wr, eivlen);
791
792 if (s->method->ssl3_enc->enc(sc, &wr, 1, 1, NULL, mac_size) < 1) {
793 if (!ossl_statem_in_error(sc)) {
794 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
795 }
796 return -1;
797 }
798
799 if (SSL_WRITE_ETM(sc) && mac_size != 0) {
800 if (!s->method->ssl3_enc->mac(sc, &wr,
801 &(p[SSL3_RECORD_get_length(&wr)]), 1)) {
802 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
803 return -1;
804 }
805 SSL3_RECORD_add_length(&wr, mac_size);
806 }
807
808 /* record length after mac and block padding */
809
810 /* there's only one epoch between handshake and app data */
811
812 s2n(sc->rlayer.d->w_epoch, pseq);
813
814 memcpy(pseq, &(sc->rlayer.write_sequence[2]), 6);
815 pseq += 6;
816 s2n(SSL3_RECORD_get_length(&wr), pseq);
817
818 if (sc->msg_callback)
819 sc->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
820 DTLS1_RT_HEADER_LENGTH, s, sc->msg_callback_arg);
821
822 /*
823 * we should now have wr.data pointing to the encrypted data, which is
824 * wr->length long
825 */
826 SSL3_RECORD_set_type(&wr, type); /* not needed but helps for debugging */
827 SSL3_RECORD_add_length(&wr, DTLS1_RT_HEADER_LENGTH);
828
829 ssl3_record_sequence_update(&(sc->rlayer.write_sequence[0]));
830
831 if (create_empty_fragment) {
832 /*
833 * we are in a recursive call; just return the length, don't write
834 * out anything here
835 */
836 *written = wr.length;
837 return 1;
838 }
839
840 /* now let's set up wb */
841 SSL3_BUFFER_set_left(wb, prefix_len + SSL3_RECORD_get_length(&wr));
842 SSL3_BUFFER_set_offset(wb, 0);
843
844 /*
845 * memorize arguments so that ssl3_write_pending can detect bad write
846 * retries later
847 */
848 sc->rlayer.wpend_tot = len;
849 sc->rlayer.wpend_buf = buf;
850 sc->rlayer.wpend_type = type;
851 sc->rlayer.wpend_ret = len;
852
853 /* we now just need to write the buffer. Calls SSLfatal() as required. */
854 return ssl3_write_pending(sc, type, buf, len, written);
855 }
856
857 void dtls1_reset_seq_numbers(SSL_CONNECTION *s, int rw)
858 {
859 unsigned char *seq;
860 unsigned int seq_bytes = sizeof(s->rlayer.read_sequence);
861
862 if (rw & SSL3_CC_READ) {
863 seq = s->rlayer.read_sequence;
864 s->rlayer.d->r_epoch++;
865 memcpy(&s->rlayer.d->bitmap, &s->rlayer.d->next_bitmap,
866 sizeof(s->rlayer.d->bitmap));
867 memset(&s->rlayer.d->next_bitmap, 0, sizeof(s->rlayer.d->next_bitmap));
868
869 /*
870 * We must not use any buffered messages received from the previous
871 * epoch
872 */
873 dtls1_clear_received_buffer(s);
874 } else {
875 seq = s->rlayer.write_sequence;
876 memcpy(s->rlayer.d->last_write_sequence, seq,
877 sizeof(s->rlayer.write_sequence));
878 s->rlayer.d->w_epoch++;
879 }
880
881 memset(seq, 0, seq_bytes);
882 }