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