Fix missing return value checks.
[openssl.git] / ssl / s3_both.c
1 /* ssl/s3_both.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116
117 #include <limits.h>
118 #include <string.h>
119 #include <stdio.h>
120 #include "ssl_locl.h"
121 #include <openssl/buffer.h>
122 #include <openssl/rand.h>
123 #include <openssl/objects.h>
124 #include <openssl/evp.h>
125 #include <openssl/x509.h>
126
127 /*
128  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
129  * SSL3_RT_CHANGE_CIPHER_SPEC)
130  */
131 int ssl3_do_write(SSL *s, int type)
132 {
133     int ret;
134
135     ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
136                            s->init_num);
137     if (ret < 0)
138         return (-1);
139     if (type == SSL3_RT_HANDSHAKE)
140         /*
141          * should not be done for 'Hello Request's, but in that case we'll
142          * ignore the result anyway
143          */
144         ssl3_finish_mac(s, (unsigned char *)&s->init_buf->data[s->init_off],
145                         ret);
146
147     if (ret == s->init_num) {
148         if (s->msg_callback)
149             s->msg_callback(1, s->version, type, s->init_buf->data,
150                             (size_t)(s->init_off + s->init_num), s,
151                             s->msg_callback_arg);
152         return (1);
153     }
154     s->init_off += ret;
155     s->init_num -= ret;
156     return (0);
157 }
158
159 int ssl3_send_finished(SSL *s, int a, int b, const char *sender, int slen)
160 {
161     unsigned char *p;
162     int i;
163     unsigned long l;
164
165     if (s->state == a) {
166         p = ssl_handshake_start(s);
167
168         i = s->method->ssl3_enc->final_finish_mac(s,
169                                                   sender, slen,
170                                                   s->s3->tmp.finish_md);
171         if (i == 0)
172             return 0;
173         s->s3->tmp.finish_md_len = i;
174         memcpy(p, s->s3->tmp.finish_md, i);
175         l = i;
176
177         /*
178          * Copy the finished so we can use it for renegotiation checks
179          */
180         if (s->type == SSL_ST_CONNECT) {
181             OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
182             memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md, i);
183             s->s3->previous_client_finished_len = i;
184         } else {
185             OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
186             memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md, i);
187             s->s3->previous_server_finished_len = i;
188         }
189
190 #ifdef OPENSSL_SYS_WIN16
191         /*
192          * MSVC 1.5 does not clear the top bytes of the word unless I do
193          * this.
194          */
195         l &= 0xffff;
196 #endif
197         ssl_set_handshake_header(s, SSL3_MT_FINISHED, l);
198         s->state = b;
199     }
200
201     /* SSL3_ST_SEND_xxxxxx_HELLO_B */
202     return ssl_do_write(s);
203 }
204
205 #ifndef OPENSSL_NO_NEXTPROTONEG
206 /*
207  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
208  * to far.
209  */
210 static void ssl3_take_mac(SSL *s)
211 {
212     const char *sender;
213     int slen;
214     /*
215      * If no new cipher setup return immediately: other functions will set
216      * the appropriate error.
217      */
218     if (s->s3->tmp.new_cipher == NULL)
219         return;
220     if (s->state & SSL_ST_CONNECT) {
221         sender = s->method->ssl3_enc->server_finished_label;
222         slen = s->method->ssl3_enc->server_finished_label_len;
223     } else {
224         sender = s->method->ssl3_enc->client_finished_label;
225         slen = s->method->ssl3_enc->client_finished_label_len;
226     }
227
228     s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
229                                                                           sender,
230                                                                           slen,
231                                                                           s->s3->tmp.peer_finish_md);
232 }
233 #endif
234
235 int ssl3_get_finished(SSL *s, int a, int b)
236 {
237     int al, i, ok;
238     long n;
239     unsigned char *p;
240
241 #ifdef OPENSSL_NO_NEXTPROTONEG
242     /*
243      * the mac has already been generated when we received the change cipher
244      * spec message and is in s->s3->tmp.peer_finish_md
245      */
246 #endif
247
248     /* 64 argument should actually be 36+4 :-) */
249     n = s->method->ssl_get_message(s, a, b, SSL3_MT_FINISHED, 64, &ok);
250
251     if (!ok)
252         return ((int)n);
253
254     /* If this occurs, we have missed a message */
255     if (!s->s3->change_cipher_spec) {
256         al = SSL_AD_UNEXPECTED_MESSAGE;
257         SSLerr(SSL_F_SSL3_GET_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
258         goto f_err;
259     }
260     s->s3->change_cipher_spec = 0;
261
262     p = (unsigned char *)s->init_msg;
263     i = s->s3->tmp.peer_finish_md_len;
264
265     if (i != n) {
266         al = SSL_AD_DECODE_ERROR;
267         SSLerr(SSL_F_SSL3_GET_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
268         goto f_err;
269     }
270
271     if (CRYPTO_memcmp(p, s->s3->tmp.peer_finish_md, i) != 0) {
272         al = SSL_AD_DECRYPT_ERROR;
273         SSLerr(SSL_F_SSL3_GET_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
274         goto f_err;
275     }
276
277     /*
278      * Copy the finished so we can use it for renegotiation checks
279      */
280     if (s->type == SSL_ST_ACCEPT) {
281         OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
282         memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md, i);
283         s->s3->previous_client_finished_len = i;
284     } else {
285         OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
286         memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md, i);
287         s->s3->previous_server_finished_len = i;
288     }
289
290     return (1);
291  f_err:
292     ssl3_send_alert(s, SSL3_AL_FATAL, al);
293     return (0);
294 }
295
296 /*-
297  * for these 2 messages, we need to
298  * ssl->enc_read_ctx                    re-init
299  * ssl->s3->read_sequence               zero
300  * ssl->s3->read_mac_secret             re-init
301  * ssl->session->read_sym_enc           assign
302  * ssl->session->read_compression       assign
303  * ssl->session->read_hash              assign
304  */
305 int ssl3_send_change_cipher_spec(SSL *s, int a, int b)
306 {
307     unsigned char *p;
308
309     if (s->state == a) {
310         p = (unsigned char *)s->init_buf->data;
311         *p = SSL3_MT_CCS;
312         s->init_num = 1;
313         s->init_off = 0;
314
315         s->state = b;
316     }
317
318     /* SSL3_ST_CW_CHANGE_B */
319     return (ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
320 }
321
322 unsigned long ssl3_output_cert_chain(SSL *s, CERT_PKEY *cpk)
323 {
324     unsigned char *p;
325     unsigned long l = 3 + SSL_HM_HEADER_LENGTH(s);
326
327     if (!ssl_add_cert_chain(s, cpk, &l))
328         return 0;
329
330     l -= 3 + SSL_HM_HEADER_LENGTH(s);
331     p = ssl_handshake_start(s);
332     l2n3(l, p);
333     l += 3;
334     ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE, l);
335     return l + SSL_HM_HEADER_LENGTH(s);
336 }
337
338 /*
339  * Obtain handshake message of message type 'mt' (any if mt == -1), maximum
340  * acceptable body length 'max'. The first four bytes (msg_type and length)
341  * are read in state 'st1', the body is read in state 'stn'.
342  */
343 long ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
344 {
345     unsigned char *p;
346     unsigned long l;
347     long n;
348     int i, al;
349
350     if (s->s3->tmp.reuse_message) {
351         s->s3->tmp.reuse_message = 0;
352         if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
353             al = SSL_AD_UNEXPECTED_MESSAGE;
354             SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
355             goto f_err;
356         }
357         *ok = 1;
358         s->state = stn;
359         s->init_msg = s->init_buf->data + 4;
360         s->init_num = (int)s->s3->tmp.message_size;
361         return s->init_num;
362     }
363
364     p = (unsigned char *)s->init_buf->data;
365
366     if (s->state == st1) {      /* s->init_num < 4 */
367         int skip_message;
368
369         do {
370             while (s->init_num < 4) {
371                 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
372                                               &p[s->init_num],
373                                               4 - s->init_num, 0);
374                 if (i <= 0) {
375                     s->rwstate = SSL_READING;
376                     *ok = 0;
377                     return i;
378                 }
379                 s->init_num += i;
380             }
381
382             skip_message = 0;
383             if (!s->server)
384                 if (p[0] == SSL3_MT_HELLO_REQUEST)
385                     /*
386                      * The server may always send 'Hello Request' messages --
387                      * we are doing a handshake anyway now, so ignore them if
388                      * their format is correct. Does not count for 'Finished'
389                      * MAC.
390                      */
391                     if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
392                         s->init_num = 0;
393                         skip_message = 1;
394
395                         if (s->msg_callback)
396                             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
397                                             p, 4, s, s->msg_callback_arg);
398                     }
399         }
400         while (skip_message);
401
402         /* s->init_num == 4 */
403
404         if ((mt >= 0) && (*p != mt)) {
405             al = SSL_AD_UNEXPECTED_MESSAGE;
406             SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
407             goto f_err;
408         }
409
410         s->s3->tmp.message_type = *(p++);
411
412         n2l3(p, l);
413         if (l > (unsigned long)max) {
414             al = SSL_AD_ILLEGAL_PARAMETER;
415             SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
416             goto f_err;
417         }
418         if (l > (INT_MAX - 4)) { /* BUF_MEM_grow takes an 'int' parameter */
419             al = SSL_AD_ILLEGAL_PARAMETER;
420             SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
421             goto f_err;
422         }
423         if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l + 4)) {
424             SSLerr(SSL_F_SSL3_GET_MESSAGE, ERR_R_BUF_LIB);
425             goto err;
426         }
427         s->s3->tmp.message_size = l;
428         s->state = stn;
429
430         s->init_msg = s->init_buf->data + 4;
431         s->init_num = 0;
432     }
433
434     /* next state (stn) */
435     p = s->init_msg;
436     n = s->s3->tmp.message_size - s->init_num;
437     while (n > 0) {
438         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &p[s->init_num],
439                                       n, 0);
440         if (i <= 0) {
441             s->rwstate = SSL_READING;
442             *ok = 0;
443             return i;
444         }
445         s->init_num += i;
446         n -= i;
447     }
448
449 #ifndef OPENSSL_NO_NEXTPROTONEG
450     /*
451      * If receiving Finished, record MAC of prior handshake messages for
452      * Finished verification.
453      */
454     if (*s->init_buf->data == SSL3_MT_FINISHED)
455         ssl3_take_mac(s);
456 #endif
457
458     /* Feed this message into MAC computation. */
459     ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, s->init_num + 4);
460     if (s->msg_callback)
461         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
462                         (size_t)s->init_num + 4, s, s->msg_callback_arg);
463     *ok = 1;
464     return s->init_num;
465  f_err:
466     ssl3_send_alert(s, SSL3_AL_FATAL, al);
467  err:
468     *ok = 0;
469     return (-1);
470 }
471
472 int ssl_cert_type(X509 *x, EVP_PKEY *pkey)
473 {
474     EVP_PKEY *pk;
475     int ret = -1, i;
476
477     if (pkey == NULL)
478         pk = X509_get_pubkey(x);
479     else
480         pk = pkey;
481     if (pk == NULL)
482         goto err;
483
484     i = pk->type;
485     if (i == EVP_PKEY_RSA) {
486         ret = SSL_PKEY_RSA_ENC;
487     } else if (i == EVP_PKEY_DSA) {
488         ret = SSL_PKEY_DSA_SIGN;
489     }
490 #ifndef OPENSSL_NO_EC
491     else if (i == EVP_PKEY_EC) {
492         ret = SSL_PKEY_ECC;
493     }
494 #endif
495     else if (i == NID_id_GostR3410_94 || i == NID_id_GostR3410_94_cc) {
496         ret = SSL_PKEY_GOST94;
497     } else if (i == NID_id_GostR3410_2001 || i == NID_id_GostR3410_2001_cc) {
498         ret = SSL_PKEY_GOST01;
499     } else if (x && (i == EVP_PKEY_DH || i == EVP_PKEY_DHX)) {
500         /*
501          * For DH two cases: DH certificate signed with RSA and DH
502          * certificate signed with DSA.
503          */
504         i = X509_certificate_type(x, pk);
505         if (i & EVP_PKS_RSA)
506             ret = SSL_PKEY_DH_RSA;
507         else if (i & EVP_PKS_DSA)
508             ret = SSL_PKEY_DH_DSA;
509     }
510
511  err:
512     if (!pkey)
513         EVP_PKEY_free(pk);
514     return (ret);
515 }
516
517 int ssl_verify_alarm_type(long type)
518 {
519     int al;
520
521     switch (type) {
522     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
523     case X509_V_ERR_UNABLE_TO_GET_CRL:
524     case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
525         al = SSL_AD_UNKNOWN_CA;
526         break;
527     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
528     case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
529     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
530     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
531     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
532     case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
533     case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
534     case X509_V_ERR_CERT_NOT_YET_VALID:
535     case X509_V_ERR_CRL_NOT_YET_VALID:
536     case X509_V_ERR_CERT_UNTRUSTED:
537     case X509_V_ERR_CERT_REJECTED:
538         al = SSL_AD_BAD_CERTIFICATE;
539         break;
540     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
541     case X509_V_ERR_CRL_SIGNATURE_FAILURE:
542         al = SSL_AD_DECRYPT_ERROR;
543         break;
544     case X509_V_ERR_CERT_HAS_EXPIRED:
545     case X509_V_ERR_CRL_HAS_EXPIRED:
546         al = SSL_AD_CERTIFICATE_EXPIRED;
547         break;
548     case X509_V_ERR_CERT_REVOKED:
549         al = SSL_AD_CERTIFICATE_REVOKED;
550         break;
551     case X509_V_ERR_OUT_OF_MEM:
552         al = SSL_AD_INTERNAL_ERROR;
553         break;
554     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
555     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
556     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
557     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
558     case X509_V_ERR_CERT_CHAIN_TOO_LONG:
559     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
560     case X509_V_ERR_INVALID_CA:
561         al = SSL_AD_UNKNOWN_CA;
562         break;
563     case X509_V_ERR_APPLICATION_VERIFICATION:
564         al = SSL_AD_HANDSHAKE_FAILURE;
565         break;
566     case X509_V_ERR_INVALID_PURPOSE:
567         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
568         break;
569     default:
570         al = SSL_AD_CERTIFICATE_UNKNOWN;
571         break;
572     }
573     return (al);
574 }
575
576 #ifndef OPENSSL_NO_BUF_FREELISTS
577 /*-
578  * On some platforms, malloc() performance is bad enough that you can't just
579  * free() and malloc() buffers all the time, so we need to use freelists from
580  * unused buffers.  Currently, each freelist holds memory chunks of only a
581  * given size (list->chunklen); other sized chunks are freed and malloced.
582  * This doesn't help much if you're using many different SSL option settings
583  * with a given context.  (The options affecting buffer size are
584  * max_send_fragment, read buffer vs write buffer,
585  * SSL_OP_MICROSOFT_BIG_WRITE_BUFFER, SSL_OP_NO_COMPRESSION, and
586  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS.)  Using a separate freelist for every
587  * possible size is not an option, since max_send_fragment can take on many
588  * different values.
589  *
590  * If you are on a platform with a slow malloc(), and you're using SSL
591  * connections with many different settings for these options, and you need to
592  * use the SSL_MOD_RELEASE_BUFFERS feature, you have a few options:
593  *    - Link against a faster malloc implementation.
594  *    - Use a separate SSL_CTX for each option set.
595  *    - Improve this code.
596  */
597 static void *freelist_extract(SSL_CTX *ctx, int for_read, int sz)
598 {
599     SSL3_BUF_FREELIST *list;
600     SSL3_BUF_FREELIST_ENTRY *ent = NULL;
601     void *result = NULL;
602
603     CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
604     list = for_read ? ctx->rbuf_freelist : ctx->wbuf_freelist;
605     if (list != NULL && sz == (int)list->chunklen)
606         ent = list->head;
607     if (ent != NULL) {
608         list->head = ent->next;
609         result = ent;
610         if (--list->len == 0)
611             list->chunklen = 0;
612     }
613     CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
614     if (!result)
615         result = OPENSSL_malloc(sz);
616     return result;
617 }
618
619 static void freelist_insert(SSL_CTX *ctx, int for_read, size_t sz, void *mem)
620 {
621     SSL3_BUF_FREELIST *list;
622     SSL3_BUF_FREELIST_ENTRY *ent;
623
624     CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
625     list = for_read ? ctx->rbuf_freelist : ctx->wbuf_freelist;
626     if (list != NULL &&
627         (sz == list->chunklen || list->chunklen == 0) &&
628         list->len < ctx->freelist_max_len && sz >= sizeof(*ent)) {
629         list->chunklen = sz;
630         ent = mem;
631         ent->next = list->head;
632         list->head = ent;
633         ++list->len;
634         mem = NULL;
635     }
636
637     CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
638     if (mem)
639         OPENSSL_free(mem);
640 }
641 #else
642 # define freelist_extract(c,fr,sz) OPENSSL_malloc(sz)
643 # define freelist_insert(c,fr,sz,m) OPENSSL_free(m)
644 #endif
645
646 int ssl3_setup_read_buffer(SSL *s)
647 {
648     unsigned char *p;
649     size_t len, align = 0, headerlen;
650
651     if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
652         headerlen = DTLS1_RT_HEADER_LENGTH;
653     else
654         headerlen = SSL3_RT_HEADER_LENGTH;
655
656 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
657     align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
658 #endif
659
660     if (s->s3->rbuf.buf == NULL) {
661         len = SSL3_RT_MAX_PLAIN_LENGTH
662             + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
663         if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) {
664             s->s3->init_extra = 1;
665             len += SSL3_RT_MAX_EXTRA;
666         }
667 #ifndef OPENSSL_NO_COMP
668         if (!(s->options & SSL_OP_NO_COMPRESSION))
669             len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
670 #endif
671         if ((p = freelist_extract(s->ctx, 1, len)) == NULL)
672             goto err;
673         s->s3->rbuf.buf = p;
674         s->s3->rbuf.len = len;
675     }
676
677     s->packet = &(s->s3->rbuf.buf[0]);
678     return 1;
679
680  err:
681     SSLerr(SSL_F_SSL3_SETUP_READ_BUFFER, ERR_R_MALLOC_FAILURE);
682     return 0;
683 }
684
685 int ssl3_setup_write_buffer(SSL *s)
686 {
687     unsigned char *p;
688     size_t len, align = 0, headerlen;
689
690     if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
691         headerlen = DTLS1_RT_HEADER_LENGTH + 1;
692     else
693         headerlen = SSL3_RT_HEADER_LENGTH;
694
695 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
696     align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
697 #endif
698
699     if (s->s3->wbuf.buf == NULL) {
700         len = s->max_send_fragment
701             + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
702 #ifndef OPENSSL_NO_COMP
703         if (!(s->options & SSL_OP_NO_COMPRESSION))
704             len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
705 #endif
706         if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
707             len += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
708
709         if ((p = freelist_extract(s->ctx, 0, len)) == NULL)
710             goto err;
711         s->s3->wbuf.buf = p;
712         s->s3->wbuf.len = len;
713     }
714
715     return 1;
716
717  err:
718     SSLerr(SSL_F_SSL3_SETUP_WRITE_BUFFER, ERR_R_MALLOC_FAILURE);
719     return 0;
720 }
721
722 int ssl3_setup_buffers(SSL *s)
723 {
724     if (!ssl3_setup_read_buffer(s))
725         return 0;
726     if (!ssl3_setup_write_buffer(s))
727         return 0;
728     return 1;
729 }
730
731 int ssl3_release_write_buffer(SSL *s)
732 {
733     if (s->s3->wbuf.buf != NULL) {
734         freelist_insert(s->ctx, 0, s->s3->wbuf.len, s->s3->wbuf.buf);
735         s->s3->wbuf.buf = NULL;
736     }
737     return 1;
738 }
739
740 int ssl3_release_read_buffer(SSL *s)
741 {
742     if (s->s3->rbuf.buf != NULL) {
743         freelist_insert(s->ctx, 1, s->s3->rbuf.len, s->s3->rbuf.buf);
744         s->s3->rbuf.buf = NULL;
745     }
746     return 1;
747 }