1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /* _ _
18 * _ __ ___ ___ __| | ___ ___| | mod_ssl
19 * | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| | \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
22 * |_____|
23 * ssl_engine_io.c
24 * I/O Functions
25 */
26 /* ``MY HACK: This universe.
27 Just one little problem:
28 core keeps dumping.''
29 -- Unknown */
30 #include "ssl_private.h"
31 #include "mod_ssl.h"
32 #include "mod_ssl_openssl.h"
33 #include "apr_date.h"
34
35 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ssl, SSL, int, proxy_post_handshake,
36 (conn_rec *c,SSL *ssl),
37 (c,ssl),OK,DECLINED);
38
39 /* _________________________________________________________________
40 **
41 ** I/O Hooks
42 ** _________________________________________________________________
43 */
44
45 /* This file is designed to be the bridge between OpenSSL and httpd.
46 * However, we really don't expect anyone (let alone ourselves) to
47 * remember what is in this file. So, first, a quick overview.
48 *
49 * In this file, you will find:
50 * - ssl_io_filter_input (Apache input filter)
51 * - ssl_io_filter_output (Apache output filter)
52 *
53 * - bio_filter_in_* (OpenSSL input filter)
54 * - bio_filter_out_* (OpenSSL output filter)
55 *
56 * The input chain is roughly:
57 *
58 * ssl_io_filter_input->ssl_io_input_read->SSL_read->...
59 * ...->bio_filter_in_read->ap_get_brigade/next-httpd-filter
60 *
61 * In mortal terminology, we do the following:
62 * - Receive a request for data to the SSL input filter
63 * - Call a helper function once we know we should perform a read
64 * - Call OpenSSL's SSL_read()
65 * - SSL_read() will then call bio_filter_in_read
66 * - bio_filter_in_read will then try to fetch data from the next httpd filter
67 * - bio_filter_in_read will flatten that data and return it to SSL_read
68 * - SSL_read will then decrypt the data
69 * - ssl_io_input_read will then receive decrypted data as a char* and
70 * ensure that there were no read errors
71 * - The char* is placed in a brigade and returned
72 *
73 * Since connection-level input filters in httpd need to be able to
74 * handle AP_MODE_GETLINE calls (namely identifying LF-terminated strings),
75 * ssl_io_input_getline which will handle this special case.
76 *
77 * Due to AP_MODE_GETLINE and AP_MODE_SPECULATIVE, we may sometimes have
78 * 'leftover' decoded data which must be setaside for the next read. That
79 * is currently handled by the char_buffer_{read|write} functions. So,
80 * ssl_io_input_read may be able to fulfill reads without invoking
81 * SSL_read().
82 *
83 * Note that the filter context of ssl_io_filter_input and bio_filter_in_*
84 * are shared as bio_filter_in_ctx_t.
85 *
86 * Note that the filter is by choice limited to reading at most
87 * AP_IOBUFSIZE (8192 bytes) per call.
88 *
89 */
90
91 /* this custom BIO allows us to hook SSL_write directly into
92 * an apr_bucket_brigade and use transient buckets with the SSL
93 * malloc-ed buffer, rather than copying into a mem BIO.
94 * also allows us to pass the brigade as data is being written
95 * rather than buffering up the entire response in the mem BIO.
96 *
97 * when SSL needs to flush (e.g. SSL_accept()), it will call BIO_flush()
98 * which will trigger a call to bio_filter_out_ctrl() -> bio_filter_out_flush().
99 * so we only need to flush the output ourselves if we receive an
100 * EOS or FLUSH bucket. this was not possible with the mem BIO where we
101 * had to flush all over the place not really knowing when it was required
102 * to do so.
103 */
104
105 typedef struct {
106 SSL *pssl;
107 BIO *pbioRead;
108 BIO *pbioWrite;
109 ap_filter_t *pInputFilter;
110 ap_filter_t *pOutputFilter;
111 SSLConnRec *config;
112 } ssl_filter_ctx_t;
113
114 typedef struct {
115 ssl_filter_ctx_t *filter_ctx;
116 conn_rec *c;
117 apr_bucket_brigade *bb; /* Brigade used as a buffer. */
118 apr_status_t rc;
119 } bio_filter_out_ctx_t;
120
bio_filter_out_ctx_new(ssl_filter_ctx_t * filter_ctx,conn_rec * c)121 static bio_filter_out_ctx_t *bio_filter_out_ctx_new(ssl_filter_ctx_t *filter_ctx,
122 conn_rec *c)
123 {
124 bio_filter_out_ctx_t *outctx = apr_palloc(c->pool, sizeof(*outctx));
125
126 outctx->filter_ctx = filter_ctx;
127 outctx->c = c;
128 outctx->bb = apr_brigade_create(c->pool, c->bucket_alloc);
129
130 return outctx;
131 }
132
133 /* Pass an output brigade down the filter stack; returns 1 on success
134 * or -1 on failure. */
bio_filter_out_pass(bio_filter_out_ctx_t * outctx)135 static int bio_filter_out_pass(bio_filter_out_ctx_t *outctx)
136 {
137 AP_DEBUG_ASSERT(!APR_BRIGADE_EMPTY(outctx->bb));
138
139 outctx->rc = ap_pass_brigade(outctx->filter_ctx->pOutputFilter->next,
140 outctx->bb);
141 /* Fail if the connection was reset: */
142 if (outctx->rc == APR_SUCCESS && outctx->c->aborted) {
143 outctx->rc = APR_ECONNRESET;
144 }
145 return (outctx->rc == APR_SUCCESS) ? 1 : -1;
146 }
147
148 /* Send a FLUSH bucket down the output filter stack; returns 1 on
149 * success, -1 on failure. */
bio_filter_out_flush(BIO * bio)150 static int bio_filter_out_flush(BIO *bio)
151 {
152 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)BIO_get_data(bio);
153 apr_bucket *e;
154
155 ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, outctx->c,
156 "bio_filter_out_write: flush");
157
158 AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(outctx->bb));
159
160 e = apr_bucket_flush_create(outctx->bb->bucket_alloc);
161 APR_BRIGADE_INSERT_TAIL(outctx->bb, e);
162
163 return bio_filter_out_pass(outctx);
164 }
165
bio_filter_create(BIO * bio)166 static int bio_filter_create(BIO *bio)
167 {
168 BIO_set_shutdown(bio, 1);
169 BIO_set_init(bio, 1);
170 #if MODSSL_USE_OPENSSL_PRE_1_1_API
171 /* No setter method for OpenSSL 1.1.0 available,
172 * but I can't find any functional use of the
173 * "num" field there either.
174 */
175 bio->num = -1;
176 #endif
177 BIO_set_data(bio, NULL);
178
179 return 1;
180 }
181
bio_filter_destroy(BIO * bio)182 static int bio_filter_destroy(BIO *bio)
183 {
184 if (bio == NULL) {
185 return 0;
186 }
187
188 /* nothing to free here.
189 * apache will destroy the bucket brigade for us
190 */
191 return 1;
192 }
193
bio_filter_out_read(BIO * bio,char * out,int outl)194 static int bio_filter_out_read(BIO *bio, char *out, int outl)
195 {
196 /* this is never called */
197 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)BIO_get_data(bio);
198 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, outctx->c,
199 "BUG: %s() should not be called", "bio_filter_out_read");
200 AP_DEBUG_ASSERT(0);
201 return -1;
202 }
203
bio_filter_out_write(BIO * bio,const char * in,int inl)204 static int bio_filter_out_write(BIO *bio, const char *in, int inl)
205 {
206 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)BIO_get_data(bio);
207 apr_bucket *e;
208 int need_flush;
209
210 BIO_clear_retry_flags(bio);
211
212 /* Abort early if the client has initiated a renegotiation. */
213 if (outctx->filter_ctx->config->reneg_state == RENEG_ABORT) {
214 outctx->rc = APR_ECONNABORTED;
215 return -1;
216 }
217
218 ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, outctx->c,
219 "bio_filter_out_write: %i bytes", inl);
220
221 /* Use a transient bucket for the output data - any downstream
222 * filter must setaside if necessary. */
223 e = apr_bucket_transient_create(in, inl, outctx->bb->bucket_alloc);
224 APR_BRIGADE_INSERT_TAIL(outctx->bb, e);
225
226 /* In theory, OpenSSL should flush as necessary, but it is known
227 * not to do so correctly in some cases (< 0.9.8m; see PR 46952),
228 * or on the proxy/client side (after ssl23_client_hello(), e.g.
229 * ssl/proxy.t test suite).
230 *
231 * Historically, this flush call was performed only for an SSLv2
232 * connection or for a proxy connection. Calling _out_flush can
233 * be expensive in cases where requests/responses are pipelined,
234 * so limit the performance impact to handshake time.
235 */
236 #if OPENSSL_VERSION_NUMBER < 0x0009080df
237 need_flush = !SSL_is_init_finished(outctx->filter_ctx->pssl);
238 #else
239 need_flush = SSL_in_connect_init(outctx->filter_ctx->pssl);
240 #endif
241 if (need_flush) {
242 e = apr_bucket_flush_create(outctx->bb->bucket_alloc);
243 APR_BRIGADE_INSERT_TAIL(outctx->bb, e);
244 }
245
246 if (bio_filter_out_pass(outctx) < 0) {
247 return -1;
248 }
249
250 return inl;
251 }
252
bio_filter_out_ctrl(BIO * bio,int cmd,long num,void * ptr)253 static long bio_filter_out_ctrl(BIO *bio, int cmd, long num, void *ptr)
254 {
255 long ret = 0;
256 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)BIO_get_data(bio);
257
258 switch (cmd) {
259 case BIO_CTRL_RESET:
260 case BIO_CTRL_EOF:
261 case BIO_C_SET_BUF_MEM_EOF_RETURN:
262 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, outctx->c,
263 "output bio: unhandled control %d", cmd);
264 ret = 0;
265 break;
266 case BIO_CTRL_WPENDING:
267 case BIO_CTRL_PENDING:
268 case BIO_CTRL_INFO:
269 ret = 0;
270 break;
271 case BIO_CTRL_GET_CLOSE:
272 ret = (long)BIO_get_shutdown(bio);
273 break;
274 case BIO_CTRL_SET_CLOSE:
275 BIO_set_shutdown(bio, (int)num);
276 break;
277 case BIO_CTRL_FLUSH:
278 ret = bio_filter_out_flush(bio);
279 break;
280 case BIO_CTRL_DUP:
281 ret = 1;
282 break;
283 /* N/A */
284 case BIO_C_SET_BUF_MEM:
285 case BIO_C_GET_BUF_MEM_PTR:
286 /* we don't care */
287 case BIO_CTRL_PUSH:
288 case BIO_CTRL_POP:
289 default:
290 ret = 0;
291 break;
292 }
293
294 return ret;
295 }
296
bio_filter_out_gets(BIO * bio,char * buf,int size)297 static int bio_filter_out_gets(BIO *bio, char *buf, int size)
298 {
299 /* this is never called */
300 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)BIO_get_data(bio);
301 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, outctx->c,
302 "BUG: %s() should not be called", "bio_filter_out_gets");
303 AP_DEBUG_ASSERT(0);
304 return -1;
305 }
306
bio_filter_out_puts(BIO * bio,const char * str)307 static int bio_filter_out_puts(BIO *bio, const char *str)
308 {
309 /* this is never called */
310 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)BIO_get_data(bio);
311 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, outctx->c,
312 "BUG: %s() should not be called", "bio_filter_out_puts");
313 AP_DEBUG_ASSERT(0);
314 return -1;
315 }
316
317 typedef struct {
318 int length;
319 char *value;
320 } char_buffer_t;
321
322 typedef struct {
323 SSL *ssl;
324 BIO *bio_out;
325 ap_filter_t *f;
326 apr_status_t rc;
327 ap_input_mode_t mode;
328 apr_read_type_e block;
329 apr_bucket_brigade *bb;
330 char_buffer_t cbuf;
331 apr_pool_t *pool;
332 char buffer[AP_IOBUFSIZE];
333 ssl_filter_ctx_t *filter_ctx;
334 } bio_filter_in_ctx_t;
335
336 /*
337 * this char_buffer api might seem silly, but we don't need to copy
338 * any of this data and we need to remember the length.
339 */
340
341 /* Copy up to INL bytes from the char_buffer BUFFER into IN. Note
342 * that due to the strange way this API is designed/used, the
343 * char_buffer object is used to cache a segment of inctx->buffer, and
344 * then this function called to copy (part of) that segment to the
345 * beginning of inctx->buffer. So the segments to copy cannot be
346 * presumed to be non-overlapping, and memmove must be used. */
char_buffer_read(char_buffer_t * buffer,char * in,int inl)347 static int char_buffer_read(char_buffer_t *buffer, char *in, int inl)
348 {
349 if (!buffer->length) {
350 return 0;
351 }
352
353 if (buffer->length > inl) {
354 /* we have enough to fill the caller's buffer */
355 memmove(in, buffer->value, inl);
356 buffer->value += inl;
357 buffer->length -= inl;
358 }
359 else {
360 /* swallow remainder of the buffer */
361 memmove(in, buffer->value, buffer->length);
362 inl = buffer->length;
363 buffer->value = NULL;
364 buffer->length = 0;
365 }
366
367 return inl;
368 }
369
char_buffer_write(char_buffer_t * buffer,char * in,int inl)370 static int char_buffer_write(char_buffer_t *buffer, char *in, int inl)
371 {
372 buffer->value = in;
373 buffer->length = inl;
374 return inl;
375 }
376
377 /* This function will read from a brigade and discard the read buckets as it
378 * proceeds. It will read at most *len bytes.
379 */
brigade_consume(apr_bucket_brigade * bb,apr_read_type_e block,char * c,apr_size_t * len)380 static apr_status_t brigade_consume(apr_bucket_brigade *bb,
381 apr_read_type_e block,
382 char *c, apr_size_t *len)
383 {
384 apr_size_t actual = 0;
385 apr_status_t status = APR_SUCCESS;
386
387 while (!APR_BRIGADE_EMPTY(bb)) {
388 apr_bucket *b = APR_BRIGADE_FIRST(bb);
389 const char *str;
390 apr_size_t str_len;
391 apr_size_t consume;
392
393 /* Justin points out this is an http-ism that might
394 * not fit if brigade_consume is added to APR. Perhaps
395 * apr_bucket_read(eos_bucket) should return APR_EOF?
396 * Then this becomes mainline instead of a one-off.
397 */
398 if (APR_BUCKET_IS_EOS(b)) {
399 status = APR_EOF;
400 break;
401 }
402
403 /* The reason I'm not offering brigade_consume yet
404 * across to apr-util is that the following call
405 * illustrates how borked that API really is. For
406 * this sort of case (caller provided buffer) it
407 * would be much more trivial for apr_bucket_consume
408 * to do all the work that follows, based on the
409 * particular characteristics of the bucket we are
410 * consuming here.
411 */
412 status = apr_bucket_read(b, &str, &str_len, block);
413
414 if (status != APR_SUCCESS) {
415 if (APR_STATUS_IS_EOF(status)) {
416 /* This stream bucket was consumed */
417 apr_bucket_delete(b);
418 continue;
419 }
420 break;
421 }
422
423 if (str_len > 0) {
424 /* Do not block once some data has been consumed */
425 block = APR_NONBLOCK_READ;
426
427 /* Assure we don't overflow. */
428 consume = (str_len + actual > *len) ? *len - actual : str_len;
429
430 memcpy(c, str, consume);
431
432 c += consume;
433 actual += consume;
434
435 if (consume >= b->length) {
436 /* This physical bucket was consumed */
437 apr_bucket_delete(b);
438 }
439 else {
440 /* Only part of this physical bucket was consumed */
441 b->start += consume;
442 b->length -= consume;
443 }
444 }
445 else if (b->length == 0) {
446 apr_bucket_delete(b);
447 }
448
449 /* This could probably be actual == *len, but be safe from stray
450 * photons. */
451 if (actual >= *len) {
452 break;
453 }
454 }
455
456 *len = actual;
457 return status;
458 }
459
460 /*
461 * this is the function called by SSL_read()
462 */
bio_filter_in_read(BIO * bio,char * in,int inlen)463 static int bio_filter_in_read(BIO *bio, char *in, int inlen)
464 {
465 apr_size_t inl = inlen;
466 bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)BIO_get_data(bio);
467 apr_read_type_e block = inctx->block;
468
469 inctx->rc = APR_SUCCESS;
470
471 /* OpenSSL catches this case, so should we. */
472 if (!in)
473 return 0;
474
475 BIO_clear_retry_flags(bio);
476
477 /* Abort early if the client has initiated a renegotiation. */
478 if (inctx->filter_ctx->config->reneg_state == RENEG_ABORT) {
479 inctx->rc = APR_ECONNABORTED;
480 return -1;
481 }
482
483 if (!inctx->bb) {
484 inctx->rc = APR_EOF;
485 return -1;
486 }
487
488 if (APR_BRIGADE_EMPTY(inctx->bb)) {
489
490 inctx->rc = ap_get_brigade(inctx->f->next, inctx->bb,
491 AP_MODE_READBYTES, block,
492 inl);
493
494 /* If the read returns EAGAIN or success with an empty
495 * brigade, return an error after setting the retry flag;
496 * SSL_read() will then return -1, and SSL_get_error() will
497 * indicate SSL_ERROR_WANT_READ. */
498 if (APR_STATUS_IS_EAGAIN(inctx->rc) || APR_STATUS_IS_EINTR(inctx->rc)
499 || (inctx->rc == APR_SUCCESS && APR_BRIGADE_EMPTY(inctx->bb))) {
500 BIO_set_retry_read(bio);
501 return -1;
502 }
503
504 if (block == APR_BLOCK_READ
505 && APR_STATUS_IS_TIMEUP(inctx->rc)
506 && APR_BRIGADE_EMPTY(inctx->bb)) {
507 /* don't give up, just return the timeout */
508 return -1;
509 }
510 if (inctx->rc != APR_SUCCESS) {
511 /* Unexpected errors discard the brigade */
512 apr_brigade_cleanup(inctx->bb);
513 inctx->bb = NULL;
514 return -1;
515 }
516 }
517
518 inctx->rc = brigade_consume(inctx->bb, block, in, &inl);
519
520 if (inctx->rc == APR_SUCCESS) {
521 return (int)inl;
522 }
523
524 if (APR_STATUS_IS_EAGAIN(inctx->rc)
525 || APR_STATUS_IS_EINTR(inctx->rc)) {
526 BIO_set_retry_read(bio);
527 return (int)inl;
528 }
529
530 /* Unexpected errors and APR_EOF clean out the brigade.
531 * Subsequent calls will return APR_EOF.
532 */
533 apr_brigade_cleanup(inctx->bb);
534 inctx->bb = NULL;
535
536 if (APR_STATUS_IS_EOF(inctx->rc) && inl) {
537 /* Provide the results of this read pass,
538 * without resetting the BIO retry_read flag
539 */
540 return (int)inl;
541 }
542
543 return -1;
544 }
545
bio_filter_in_write(BIO * bio,const char * in,int inl)546 static int bio_filter_in_write(BIO *bio, const char *in, int inl)
547 {
548 bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)BIO_get_data(bio);
549 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, inctx->f->c,
550 "BUG: %s() should not be called", "bio_filter_in_write");
551 AP_DEBUG_ASSERT(0);
552 return -1;
553 }
554
bio_filter_in_puts(BIO * bio,const char * str)555 static int bio_filter_in_puts(BIO *bio, const char *str)
556 {
557 bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)BIO_get_data(bio);
558 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, inctx->f->c,
559 "BUG: %s() should not be called", "bio_filter_in_puts");
560 AP_DEBUG_ASSERT(0);
561 return -1;
562 }
563
bio_filter_in_gets(BIO * bio,char * buf,int size)564 static int bio_filter_in_gets(BIO *bio, char *buf, int size)
565 {
566 bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)BIO_get_data(bio);
567 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, inctx->f->c,
568 "BUG: %s() should not be called", "bio_filter_in_gets");
569 AP_DEBUG_ASSERT(0);
570 return -1;
571 }
572
bio_filter_in_ctrl(BIO * bio,int cmd,long num,void * ptr)573 static long bio_filter_in_ctrl(BIO *bio, int cmd, long num, void *ptr)
574 {
575 bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)BIO_get_data(bio);
576 switch (cmd) {
577 #ifdef BIO_CTRL_EOF
578 case BIO_CTRL_EOF:
579 return inctx->rc == APR_EOF;
580 #endif
581 default:
582 break;
583 }
584 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, inctx->f->c,
585 "BUG: bio_filter_in_ctrl() should not be called with cmd=%i",
586 cmd);
587 return 0;
588 }
589
590 #if MODSSL_USE_OPENSSL_PRE_1_1_API
591
592 static BIO_METHOD bio_filter_out_method = {
593 BIO_TYPE_MEM,
594 "APR output filter",
595 bio_filter_out_write,
596 bio_filter_out_read, /* read is never called */
597 bio_filter_out_puts, /* puts is never called */
598 bio_filter_out_gets, /* gets is never called */
599 bio_filter_out_ctrl,
600 bio_filter_create,
601 bio_filter_destroy,
602 NULL
603 };
604
605 static BIO_METHOD bio_filter_in_method = {
606 BIO_TYPE_MEM,
607 "APR input filter",
608 bio_filter_in_write, /* write is never called */
609 bio_filter_in_read,
610 bio_filter_in_puts, /* puts is never called */
611 bio_filter_in_gets, /* gets is never called */
612 bio_filter_in_ctrl, /* ctrl is called for EOF check */
613 bio_filter_create,
614 bio_filter_destroy,
615 NULL
616 };
617
618 #else
619
620 static BIO_METHOD *bio_filter_out_method = NULL;
621 static BIO_METHOD *bio_filter_in_method = NULL;
622
init_bio_methods(void)623 void init_bio_methods(void)
624 {
625 bio_filter_out_method = BIO_meth_new(BIO_TYPE_MEM, "APR output filter");
626 BIO_meth_set_write(bio_filter_out_method, &bio_filter_out_write);
627 BIO_meth_set_read(bio_filter_out_method, &bio_filter_out_read); /* read is never called */
628 BIO_meth_set_puts(bio_filter_out_method, &bio_filter_out_puts); /* puts is never called */
629 BIO_meth_set_gets(bio_filter_out_method, &bio_filter_out_gets); /* gets is never called */
630 BIO_meth_set_ctrl(bio_filter_out_method, &bio_filter_out_ctrl);
631 BIO_meth_set_create(bio_filter_out_method, &bio_filter_create);
632 BIO_meth_set_destroy(bio_filter_out_method, &bio_filter_destroy);
633
634 bio_filter_in_method = BIO_meth_new(BIO_TYPE_MEM, "APR input filter");
635 BIO_meth_set_write(bio_filter_in_method, &bio_filter_in_write); /* write is never called */
636 BIO_meth_set_read(bio_filter_in_method, &bio_filter_in_read);
637 BIO_meth_set_puts(bio_filter_in_method, &bio_filter_in_puts); /* puts is never called */
638 BIO_meth_set_gets(bio_filter_in_method, &bio_filter_in_gets); /* gets is never called */
639 BIO_meth_set_ctrl(bio_filter_in_method, &bio_filter_in_ctrl); /* ctrl is never called */
640 BIO_meth_set_create(bio_filter_in_method, &bio_filter_create);
641 BIO_meth_set_destroy(bio_filter_in_method, &bio_filter_destroy);
642 }
643
free_bio_methods(void)644 void free_bio_methods(void)
645 {
646 BIO_meth_free(bio_filter_out_method);
647 BIO_meth_free(bio_filter_in_method);
648 }
649 #endif
650
ssl_io_input_read(bio_filter_in_ctx_t * inctx,char * buf,apr_size_t * len)651 static apr_status_t ssl_io_input_read(bio_filter_in_ctx_t *inctx,
652 char *buf,
653 apr_size_t *len)
654 {
655 apr_size_t wanted = *len;
656 apr_size_t bytes = 0;
657 int rc;
658
659 *len = 0;
660
661 /* If we have something leftover from last time, try that first. */
662 if ((bytes = char_buffer_read(&inctx->cbuf, buf, wanted))) {
663 *len = bytes;
664 if (inctx->mode == AP_MODE_SPECULATIVE) {
665 /* We want to rollback this read. */
666 if (inctx->cbuf.length > 0) {
667 inctx->cbuf.value -= bytes;
668 inctx->cbuf.length += bytes;
669 } else {
670 char_buffer_write(&inctx->cbuf, buf, (int)bytes);
671 }
672 return APR_SUCCESS;
673 }
674 /* This could probably be *len == wanted, but be safe from stray
675 * photons.
676 */
677 if (*len >= wanted) {
678 return APR_SUCCESS;
679 }
680 if (inctx->mode == AP_MODE_GETLINE) {
681 if (memchr(buf, APR_ASCII_LF, *len)) {
682 return APR_SUCCESS;
683 }
684 }
685 else {
686 /* Down to a nonblock pattern as we have some data already
687 */
688 inctx->block = APR_NONBLOCK_READ;
689 }
690 }
691
692 while (1) {
693
694 if (!inctx->filter_ctx->pssl) {
695 /* Ensure a non-zero error code is returned */
696 if (inctx->rc == APR_SUCCESS) {
697 inctx->rc = APR_EGENERAL;
698 }
699 break;
700 }
701
702 /* We rely on SSL_get_error() after the read, which requires an empty
703 * error queue before the read in order to work properly.
704 */
705 ERR_clear_error();
706
707 /* SSL_read may not read because we haven't taken enough data
708 * from the stack. This is where we want to consider all of
709 * the blocking and SPECULATIVE semantics
710 */
711 rc = SSL_read(inctx->filter_ctx->pssl, buf + bytes, wanted - bytes);
712
713 if (rc > 0) {
714 *len += rc;
715 if (inctx->mode == AP_MODE_SPECULATIVE) {
716 /* We want to rollback this read. */
717 char_buffer_write(&inctx->cbuf, buf, rc);
718 }
719 return inctx->rc;
720 }
721 else /* (rc <= 0) */ {
722 int ssl_err;
723 conn_rec *c;
724 if (rc == 0) {
725 /* If EAGAIN, we will loop given a blocking read,
726 * otherwise consider ourselves at EOF.
727 */
728 if (APR_STATUS_IS_EAGAIN(inctx->rc)
729 || APR_STATUS_IS_EINTR(inctx->rc)) {
730 /* Already read something, return APR_SUCCESS instead.
731 * On win32 in particular, but perhaps on other kernels,
732 * a blocking call isn't 'always' blocking.
733 */
734 if (*len > 0) {
735 inctx->rc = APR_SUCCESS;
736 break;
737 }
738 if (inctx->block == APR_NONBLOCK_READ) {
739 break;
740 }
741 }
742 else {
743 if (*len > 0) {
744 inctx->rc = APR_SUCCESS;
745 break;
746 }
747 }
748 }
749 ssl_err = SSL_get_error(inctx->filter_ctx->pssl, rc);
750 c = (conn_rec*)SSL_get_app_data(inctx->filter_ctx->pssl);
751
752 if (ssl_err == SSL_ERROR_WANT_READ) {
753 /*
754 * If OpenSSL wants to read more, and we were nonblocking,
755 * report as an EAGAIN. Otherwise loop, pulling more
756 * data from network filter.
757 *
758 * (This is usually the case when the client forces an SSL
759 * renegotiation which is handled implicitly by OpenSSL.)
760 */
761 inctx->rc = APR_EAGAIN;
762
763 if (*len > 0) {
764 inctx->rc = APR_SUCCESS;
765 break;
766 }
767 if (inctx->block == APR_NONBLOCK_READ) {
768 break;
769 }
770 continue; /* Blocking and nothing yet? Try again. */
771 }
772 else if (ssl_err == SSL_ERROR_SYSCALL) {
773 if (APR_STATUS_IS_EAGAIN(inctx->rc)
774 || APR_STATUS_IS_EINTR(inctx->rc)) {
775 /* Already read something, return APR_SUCCESS instead. */
776 if (*len > 0) {
777 inctx->rc = APR_SUCCESS;
778 break;
779 }
780 if (inctx->block == APR_NONBLOCK_READ) {
781 break;
782 }
783 continue; /* Blocking and nothing yet? Try again. */
784 }
785 else if (APR_STATUS_IS_TIMEUP(inctx->rc)) {
786 /* just return it, the calling layer might be fine with it,
787 and we do not want to bloat the log. */
788 }
789 else {
790 ap_log_cerror(APLOG_MARK, APLOG_INFO, inctx->rc, c, APLOGNO(01991)
791 "SSL input filter read failed.");
792 }
793 }
794 else if (rc == 0 && ssl_err == SSL_ERROR_ZERO_RETURN) {
795 inctx->rc = APR_EOF;
796 break;
797 }
798 else /* if (ssl_err == SSL_ERROR_SSL) */ {
799 /*
800 * Log SSL errors and any unexpected conditions.
801 */
802 ap_log_cerror(APLOG_MARK, APLOG_INFO, inctx->rc, c, APLOGNO(01992)
803 "SSL library error %d reading data", ssl_err);
804 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, mySrvFromConn(c));
805
806 }
807 if (rc == 0) {
808 inctx->rc = APR_EOF;
809 break;
810 }
811 if (inctx->rc == APR_SUCCESS) {
812 inctx->rc = APR_EGENERAL;
813 }
814 break;
815 }
816 }
817 return inctx->rc;
818 }
819
820 /* Read a line of input from the SSL input layer into buffer BUF of
821 * length *LEN; updating *len to reflect the length of the line
822 * including the LF character. */
ssl_io_input_getline(bio_filter_in_ctx_t * inctx,char * buf,apr_size_t * len)823 static apr_status_t ssl_io_input_getline(bio_filter_in_ctx_t *inctx,
824 char *buf,
825 apr_size_t *len)
826 {
827 const char *pos = NULL;
828 apr_status_t status;
829 apr_size_t tmplen = *len, buflen = *len, offset = 0;
830
831 *len = 0;
832
833 /*
834 * in most cases we get all the headers on the first SSL_read.
835 * however, in certain cases SSL_read will only get a partial
836 * chunk of the headers, so we try to read until LF is seen.
837 */
838
839 while (tmplen > 0) {
840 status = ssl_io_input_read(inctx, buf + offset, &tmplen);
841
842 if (status != APR_SUCCESS) {
843 if (APR_STATUS_IS_EAGAIN(status) && (*len > 0)) {
844 /* Save the part of the line we already got */
845 char_buffer_write(&inctx->cbuf, buf, *len);
846 }
847 return status;
848 }
849
850 *len += tmplen;
851
852 if ((pos = memchr(buf, APR_ASCII_LF, *len))) {
853 break;
854 }
855
856 offset += tmplen;
857 tmplen = buflen - offset;
858 }
859
860 if (pos) {
861 char *value;
862 int length;
863 apr_size_t bytes = pos - buf;
864
865 bytes += 1;
866 value = buf + bytes;
867 length = *len - bytes;
868
869 char_buffer_write(&inctx->cbuf, value, length);
870
871 *len = bytes;
872 }
873
874 return APR_SUCCESS;
875 }
876
877
ssl_filter_write(ap_filter_t * f,const char * data,apr_size_t len)878 static apr_status_t ssl_filter_write(ap_filter_t *f,
879 const char *data,
880 apr_size_t len)
881 {
882 ssl_filter_ctx_t *filter_ctx = f->ctx;
883 bio_filter_out_ctx_t *outctx;
884 int res;
885
886 /* write SSL */
887 if (filter_ctx->pssl == NULL) {
888 return APR_EGENERAL;
889 }
890
891 ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, f->c,
892 "ssl_filter_write: %"APR_SIZE_T_FMT" bytes", len);
893
894 /* We rely on SSL_get_error() after the write, which requires an empty error
895 * queue before the write in order to work properly.
896 */
897 ERR_clear_error();
898
899 outctx = (bio_filter_out_ctx_t *)BIO_get_data(filter_ctx->pbioWrite);
900 res = SSL_write(filter_ctx->pssl, (unsigned char *)data, len);
901
902 if (res < 0) {
903 int ssl_err = SSL_get_error(filter_ctx->pssl, res);
904 conn_rec *c = (conn_rec*)SSL_get_app_data(outctx->filter_ctx->pssl);
905
906 if (ssl_err == SSL_ERROR_WANT_WRITE) {
907 /*
908 * If OpenSSL wants to write more, and we were nonblocking,
909 * report as an EAGAIN. Otherwise loop, pushing more
910 * data at the network filter.
911 *
912 * (This is usually the case when the client forces an SSL
913 * renegotiation which is handled implicitly by OpenSSL.)
914 */
915 outctx->rc = APR_EAGAIN;
916 }
917 else if (ssl_err == SSL_ERROR_WANT_READ) {
918 /*
919 * If OpenSSL wants to read during write, and we were
920 * nonblocking, set the sense explicitly to read and
921 * report as an EAGAIN.
922 *
923 * (This is usually the case when the client forces an SSL
924 * renegotiation which is handled implicitly by OpenSSL.)
925 */
926 outctx->c->cs->sense = CONN_SENSE_WANT_READ;
927 outctx->rc = APR_EAGAIN;
928 ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, outctx->c,
929 "Want read during nonblocking write");
930 }
931 else if (ssl_err == SSL_ERROR_SYSCALL) {
932 ap_log_cerror(APLOG_MARK, APLOG_INFO, outctx->rc, c, APLOGNO(01993)
933 "SSL output filter write failed.");
934 }
935 else /* if (ssl_err == SSL_ERROR_SSL) */ {
936 /*
937 * Log SSL errors
938 */
939 ap_log_cerror(APLOG_MARK, APLOG_INFO, outctx->rc, c, APLOGNO(01994)
940 "SSL library error %d writing data", ssl_err);
941 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, mySrvFromConn(c));
942 }
943 if (outctx->rc == APR_SUCCESS) {
944 outctx->rc = APR_EGENERAL;
945 }
946 }
947 else if ((apr_size_t)res != len) {
948 conn_rec *c = f->c;
949 char *reason = "reason unknown";
950
951 /* XXX: probably a better way to determine this */
952 if (SSL_total_renegotiations(filter_ctx->pssl)) {
953 reason = "likely due to failed renegotiation";
954 }
955
956 ap_log_cerror(APLOG_MARK, APLOG_INFO, outctx->rc, c, APLOGNO(01995)
957 "failed to write %" APR_SSIZE_T_FMT
958 " of %" APR_SIZE_T_FMT " bytes (%s)",
959 len - (apr_size_t)res, len, reason);
960
961 outctx->rc = APR_EGENERAL;
962 }
963 return outctx->rc;
964 }
965
966 /* Just use a simple request. Any request will work for this, because
967 * we use a flag in the conn_rec->conn_vector now. The fake request just
968 * gets the request back to the Apache core so that a response can be sent.
969 * Since we use an HTTP/1.x request, we also have to inject the empty line
970 * that terminates the headers, or the core will read more data from the
971 * socket.
972 */
973 #define HTTP_ON_HTTPS_PORT \
974 "GET / HTTP/1.0" CRLF
975
976 #define HTTP_ON_HTTPS_PORT_BUCKET(alloc) \
977 apr_bucket_immortal_create(HTTP_ON_HTTPS_PORT, \
978 sizeof(HTTP_ON_HTTPS_PORT) - 1, \
979 alloc)
980
981 /* Custom apr_status_t error code, used when a plain HTTP request is
982 * received on an SSL port. */
983 #define MODSSL_ERROR_HTTP_ON_HTTPS (APR_OS_START_USERERR + 0)
984
985 /* Custom apr_status_t error code, used when the proxy cannot
986 * establish an outgoing SSL connection. */
987 #define MODSSL_ERROR_BAD_GATEWAY (APR_OS_START_USERERR + 1)
988
ssl_io_filter_disable(SSLConnRec * sslconn,bio_filter_in_ctx_t * inctx)989 static void ssl_io_filter_disable(SSLConnRec *sslconn,
990 bio_filter_in_ctx_t *inctx)
991 {
992 SSL_free(inctx->ssl);
993 sslconn->ssl = NULL;
994 inctx->ssl = NULL;
995 inctx->filter_ctx->pssl = NULL;
996 }
997
ssl_io_filter_error(bio_filter_in_ctx_t * inctx,apr_bucket_brigade * bb,apr_status_t status,int is_init)998 static apr_status_t ssl_io_filter_error(bio_filter_in_ctx_t *inctx,
999 apr_bucket_brigade *bb,
1000 apr_status_t status,
1001 int is_init)
1002 {
1003 ap_filter_t *f = inctx->f;
1004 SSLConnRec *sslconn = myConnConfig(f->c);
1005 apr_bucket *bucket;
1006 int send_eos = 1;
1007
1008 switch (status) {
1009 case MODSSL_ERROR_HTTP_ON_HTTPS:
1010 /* log the situation */
1011 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, f->c, APLOGNO(01996)
1012 "SSL handshake failed: HTTP spoken on HTTPS port; "
1013 "trying to send HTML error page");
1014 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, sslconn->server);
1015
1016 ssl_io_filter_disable(sslconn, inctx);
1017 f->c->keepalive = AP_CONN_CLOSE;
1018 if (is_init) {
1019 sslconn->non_ssl_request = NON_SSL_SEND_REQLINE;
1020 return APR_EGENERAL;
1021 }
1022 sslconn->non_ssl_request = NON_SSL_SEND_HDR_SEP;
1023
1024 /* fake the request line */
1025 bucket = HTTP_ON_HTTPS_PORT_BUCKET(f->c->bucket_alloc);
1026 send_eos = 0;
1027 break;
1028
1029 case MODSSL_ERROR_BAD_GATEWAY:
1030 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, f->c, APLOGNO(01997)
1031 "SSL handshake failed: sending 502");
1032 f->c->aborted = 1;
1033 return APR_EGENERAL;
1034
1035 default:
1036 return status;
1037 }
1038
1039 APR_BRIGADE_INSERT_TAIL(bb, bucket);
1040 if (send_eos) {
1041 bucket = apr_bucket_eos_create(f->c->bucket_alloc);
1042 APR_BRIGADE_INSERT_TAIL(bb, bucket);
1043 }
1044 return APR_SUCCESS;
1045 }
1046
1047 static const char ssl_io_filter[] = "SSL/TLS Filter";
1048 static const char ssl_io_buffer[] = "SSL/TLS Buffer";
1049 static const char ssl_io_coalesce[] = "SSL/TLS Coalescing Filter";
1050
1051 /*
1052 * Close the SSL part of the socket connection
1053 * (called immediately _before_ the socket is closed)
1054 * or called with
1055 */
ssl_filter_io_shutdown(ssl_filter_ctx_t * filter_ctx,conn_rec * c,int abortive)1056 static void ssl_filter_io_shutdown(ssl_filter_ctx_t *filter_ctx,
1057 conn_rec *c, int abortive)
1058 {
1059 SSL *ssl = filter_ctx->pssl;
1060 const char *type = "";
1061 SSLConnRec *sslconn = myConnConfig(c);
1062 int shutdown_type;
1063 int loglevel = APLOG_DEBUG;
1064 const char *logno;
1065
1066 if (!ssl) {
1067 return;
1068 }
1069
1070 /*
1071 * Now close the SSL layer of the connection. We've to take
1072 * the TLSv1 standard into account here:
1073 *
1074 * | 7.2.1. Closure alerts
1075 * |
1076 * | The client and the server must share knowledge that the connection is
1077 * | ending in order to avoid a truncation attack. Either party may
1078 * | initiate the exchange of closing messages.
1079 * |
1080 * | close_notify
1081 * | This message notifies the recipient that the sender will not send
1082 * | any more messages on this connection. The session becomes
1083 * | unresumable if any connection is terminated without proper
1084 * | close_notify messages with level equal to warning.
1085 * |
1086 * | Either party may initiate a close by sending a close_notify alert.
1087 * | Any data received after a closure alert is ignored.
1088 * |
1089 * | Each party is required to send a close_notify alert before closing
1090 * | the write side of the connection. It is required that the other party
1091 * | respond with a close_notify alert of its own and close down the
1092 * | connection immediately, discarding any pending writes. It is not
1093 * | required for the initiator of the close to wait for the responding
1094 * | close_notify alert before closing the read side of the connection.
1095 *
1096 * This means we've to send a close notify message, but haven't to wait
1097 * for the close notify of the client. Actually we cannot wait for the
1098 * close notify of the client because some clients (including Netscape
1099 * 4.x) don't send one, so we would hang.
1100 */
1101
1102 /*
1103 * exchange close notify messages, but allow the user
1104 * to force the type of handshake via SetEnvIf directive
1105 */
1106 if (abortive) {
1107 shutdown_type = SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN;
1108 type = "abortive";
1109 logno = APLOGNO(01998);
1110 loglevel = APLOG_INFO;
1111 }
1112 else switch (sslconn->shutdown_type) {
1113 case SSL_SHUTDOWN_TYPE_UNCLEAN:
1114 /* perform no close notify handshake at all
1115 (violates the SSL/TLS standard!) */
1116 shutdown_type = SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN;
1117 type = "unclean";
1118 logno = APLOGNO(01999);
1119 break;
1120 case SSL_SHUTDOWN_TYPE_ACCURATE:
1121 /* send close notify and wait for clients close notify
1122 (standard compliant, but usually causes connection hangs) */
1123 shutdown_type = 0;
1124 type = "accurate";
1125 logno = APLOGNO(02000);
1126 break;
1127 default:
1128 /*
1129 * case SSL_SHUTDOWN_TYPE_UNSET:
1130 * case SSL_SHUTDOWN_TYPE_STANDARD:
1131 */
1132 /* send close notify, but don't wait for clients close notify
1133 (standard compliant and safe, so it's the DEFAULT!) */
1134 shutdown_type = SSL_RECEIVED_SHUTDOWN;
1135 type = "standard";
1136 logno = APLOGNO(02001);
1137 break;
1138 }
1139
1140 SSL_set_shutdown(ssl, shutdown_type);
1141 modssl_smart_shutdown(ssl);
1142
1143 /* and finally log the fact that we've closed the connection */
1144 if (APLOG_CS_IS_LEVEL(c, mySrvFromConn(c), loglevel)) {
1145 /* Intentional no APLOGNO */
1146 /* logno provides APLOGNO */
1147 ap_log_cserror(APLOG_MARK, loglevel, 0, c, mySrvFromConn(c),
1148 "%sConnection closed to child %ld with %s shutdown "
1149 "(server %s)",
1150 logno, c->id, type,
1151 ssl_util_vhostid(c->pool, mySrvFromConn(c)));
1152 }
1153
1154 /* deallocate the SSL connection */
1155 if (sslconn->client_cert) {
1156 X509_free(sslconn->client_cert);
1157 sslconn->client_cert = NULL;
1158 }
1159 SSL_free(ssl);
1160 sslconn->ssl = NULL;
1161 filter_ctx->pssl = NULL; /* so filters know we've been shutdown */
1162
1163 if (abortive) {
1164 /* prevent any further I/O */
1165 c->aborted = 1;
1166 }
1167 }
1168
ssl_io_filter_cleanup(void * data)1169 static apr_status_t ssl_io_filter_cleanup(void *data)
1170 {
1171 ssl_filter_ctx_t *filter_ctx = data;
1172
1173 if (filter_ctx->pssl) {
1174 conn_rec *c = (conn_rec *)SSL_get_app_data(filter_ctx->pssl);
1175 SSLConnRec *sslconn = myConnConfig(c);
1176
1177 SSL_free(filter_ctx->pssl);
1178 sslconn->ssl = filter_ctx->pssl = NULL;
1179 }
1180
1181 return APR_SUCCESS;
1182 }
1183
1184 /*
1185 * The hook is NOT registered with ap_hook_process_connection. Instead, it is
1186 * called manually from the churn () before it tries to read any data.
1187 * There is some problem if I accept conn_rec *. Still investigating..
1188 * Adv. if conn_rec * can be accepted is we can hook this function using the
1189 * ap_hook_process_connection hook.
1190 */
1191
1192 /* Perform the SSL handshake (whether in client or server mode), if
1193 * necessary, for the given connection. */
ssl_io_filter_handshake(ssl_filter_ctx_t * filter_ctx)1194 static apr_status_t ssl_io_filter_handshake(ssl_filter_ctx_t *filter_ctx)
1195 {
1196 conn_rec *c = (conn_rec *)SSL_get_app_data(filter_ctx->pssl);
1197 SSLConnRec *sslconn = myConnConfig(c);
1198 SSLSrvConfigRec *sc;
1199 X509 *cert;
1200 int n;
1201 int ssl_err;
1202 long verify_result;
1203 server_rec *server;
1204
1205 if (SSL_is_init_finished(filter_ctx->pssl)) {
1206 return APR_SUCCESS;
1207 }
1208
1209 server = sslconn->server;
1210 if (c->outgoing) {
1211 #ifdef HAVE_TLSEXT
1212 apr_ipsubnet_t *ip;
1213 #ifdef HAVE_TLS_ALPN
1214 const char *alpn_note;
1215 apr_array_header_t *alpn_proposed = NULL;
1216 int alpn_empty_ok = 1;
1217 #endif
1218 #endif
1219 const char *hostname_note = apr_table_get(c->notes,
1220 "proxy-request-hostname");
1221 BOOL proxy_ssl_check_peer_ok = TRUE;
1222 int post_handshake_rc = OK;
1223 SSLDirConfigRec *dc;
1224
1225 dc = sslconn->dc;
1226 sc = mySrvConfig(server);
1227
1228 #ifdef HAVE_TLSEXT
1229 #ifdef HAVE_TLS_ALPN
1230 alpn_note = apr_table_get(c->notes, "proxy-request-alpn-protos");
1231 if (alpn_note) {
1232 char *protos, *s, *p, *last, *proto;
1233 apr_size_t len;
1234
1235 /* Transform the note into a protocol formatted byte array:
1236 * (len-byte proto-char+)*
1237 * We need the remote server to agree on one of these, unless 'http/1.1'
1238 * is also among our proposals. Because pre-ALPN remotes will speak this.
1239 */
1240 alpn_proposed = apr_array_make(c->pool, 3, sizeof(const char*));
1241 alpn_empty_ok = 0;
1242 s = protos = apr_pcalloc(c->pool, strlen(alpn_note)+1);
1243 p = apr_pstrdup(c->pool, alpn_note);
1244 while ((p = apr_strtok(p, ", ", &last))) {
1245 len = last - p - (*last? 1 : 0);
1246 if (len > 255) {
1247 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(03309)
1248 "ALPN proxy protocol identifier too long: %s",
1249 p);
1250 ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, server);
1251 return APR_EGENERAL;
1252 }
1253 proto = apr_pstrndup(c->pool, p, len);
1254 APR_ARRAY_PUSH(alpn_proposed, const char*) = proto;
1255 if (!strcmp("http/1.1", proto)) {
1256 alpn_empty_ok = 1;
1257 }
1258 *s++ = (unsigned char)len;
1259 while (len--) {
1260 *s++ = *p++;
1261 }
1262 p = NULL;
1263 }
1264 ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,
1265 "setting alpn protos from '%s', protolen=%d",
1266 alpn_note, (int)(s - protos));
1267 if (protos != s && SSL_set_alpn_protos(filter_ctx->pssl,
1268 (unsigned char *)protos,
1269 s - protos)) {
1270 ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, c, APLOGNO(03310)
1271 "error setting alpn protos from '%s'", alpn_note);
1272 ssl_log_ssl_error(SSLLOG_MARK, APLOG_WARNING, server);
1273 /* If ALPN was requested and we cannot do it, we must fail */
1274 return MODSSL_ERROR_BAD_GATEWAY;
1275 }
1276 }
1277 #endif /* defined HAVE_TLS_ALPN */
1278 /*
1279 * Enable SNI for backend requests. Make sure we don't do it for
1280 * pure SSLv3 connections, and also prevent IP addresses
1281 * from being included in the SNI extension. (OpenSSL would simply
1282 * pass them on, but RFC 6066 is quite clear on this: "Literal
1283 * IPv4 and IPv6 addresses are not permitted".)
1284 */
1285 if (hostname_note &&
1286 #ifndef OPENSSL_NO_SSL3
1287 dc->proxy->protocol != SSL_PROTOCOL_SSLV3 &&
1288 #endif
1289 apr_ipsubnet_create(&ip, hostname_note, NULL,
1290 c->pool) != APR_SUCCESS) {
1291 if (SSL_set_tlsext_host_name(filter_ctx->pssl, hostname_note)) {
1292 ap_log_cerror(APLOG_MARK, APLOG_TRACE3, 0, c,
1293 "SNI extension for SSL Proxy request set to '%s'",
1294 hostname_note);
1295 } else {
1296 ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, c, APLOGNO(02002)
1297 "Failed to set SNI extension for SSL Proxy "
1298 "request to '%s'", hostname_note);
1299 ssl_log_ssl_error(SSLLOG_MARK, APLOG_WARNING, server);
1300 }
1301 }
1302 #endif /* defined HAVE_TLSEXT */
1303
1304 if ((n = SSL_connect(filter_ctx->pssl)) <= 0) {
1305 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02003)
1306 "SSL Proxy connect failed");
1307 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, server);
1308 /* ensure that the SSL structures etc are freed, etc: */
1309 ssl_filter_io_shutdown(filter_ctx, c, 1);
1310 apr_table_setn(c->notes, "SSL_connect_rv", "err");
1311 return MODSSL_ERROR_BAD_GATEWAY;
1312 }
1313
1314 cert = SSL_get_peer_certificate(filter_ctx->pssl);
1315
1316 if (dc->proxy->ssl_check_peer_expire != FALSE) {
1317 if (!cert
1318 || (X509_cmp_current_time(
1319 X509_get_notBefore(cert)) >= 0)
1320 || (X509_cmp_current_time(
1321 X509_get_notAfter(cert)) <= 0)) {
1322 proxy_ssl_check_peer_ok = FALSE;
1323 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02004)
1324 "SSL Proxy: Peer certificate is expired");
1325 }
1326 }
1327 if ((dc->proxy->ssl_check_peer_name != FALSE) &&
1328 ((dc->proxy->ssl_check_peer_cn != FALSE) ||
1329 (dc->proxy->ssl_check_peer_name == TRUE)) &&
1330 hostname_note) {
1331 if (!cert
1332 || modssl_X509_match_name(c->pool, cert, hostname_note,
1333 TRUE, server) == FALSE) {
1334 proxy_ssl_check_peer_ok = FALSE;
1335 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02411)
1336 "SSL Proxy: Peer certificate does not match "
1337 "for hostname %s", hostname_note);
1338 }
1339 }
1340 else if ((dc->proxy->ssl_check_peer_cn == TRUE) &&
1341 hostname_note) {
1342 const char *hostname;
1343 int match = 0;
1344
1345 hostname = ssl_var_lookup(NULL, server, c, NULL,
1346 "SSL_CLIENT_S_DN_CN");
1347
1348 /* Do string match or simplest wildcard match if that
1349 * fails. */
1350 match = strcasecmp(hostname, hostname_note) == 0;
1351 if (!match && strncmp(hostname, "*.", 2) == 0) {
1352 const char *p = ap_strchr_c(hostname_note, '.');
1353
1354 match = p && strcasecmp(p, hostname + 1) == 0;
1355 }
1356
1357 if (!match) {
1358 proxy_ssl_check_peer_ok = FALSE;
1359 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02005)
1360 "SSL Proxy: Peer certificate CN mismatch:"
1361 " Certificate CN: %s Requested hostname: %s",
1362 hostname, hostname_note);
1363 }
1364 }
1365
1366 #ifdef HAVE_TLS_ALPN
1367 /* If we proposed ALPN protocol(s), we need to check if the server
1368 * agreed to one of them. While <https://www.rfc-editor.org/rfc/rfc7301.txt>
1369 * chapter 3.2 says the server SHALL error the handshake in such a case,
1370 * the reality is that some servers fall back to their default, e.g. http/1.1.
1371 * (we also do this right now)
1372 * We need to treat this as an error for security reasons.
1373 */
1374 if (alpn_proposed && alpn_proposed->nelts > 0) {
1375 const char *selected;
1376 unsigned int slen;
1377
1378 SSL_get0_alpn_selected(filter_ctx->pssl, (const unsigned char**)&selected, &slen);
1379 if (!selected || !slen) {
1380 /* No ALPN selection reported by the remote server. This could mean
1381 * it does not support ALPN (old server) or that it does not support
1382 * any of our proposals (Apache itself up to 2.4.48 at least did that). */
1383 if (!alpn_empty_ok) {
1384 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(10273)
1385 "SSL Proxy: Peer did not select any of our ALPN protocols [%s].",
1386 alpn_note);
1387 proxy_ssl_check_peer_ok = FALSE;
1388 }
1389 }
1390 else {
1391 const char *proto;
1392 int i, found = 0;
1393 for (i = 0; !found && i < alpn_proposed->nelts; ++i) {
1394 proto = APR_ARRAY_IDX(alpn_proposed, i, const char *);
1395 found = !strncmp(selected, proto, slen);
1396 }
1397 if (!found) {
1398 /* From a conforming peer, this should never happen,
1399 * but life always finds a way... */
1400 proto = apr_pstrndup(c->pool, selected, slen);
1401 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(10274)
1402 "SSL Proxy: Peer proposed ALPN protocol %s which is none "
1403 "of our proposals [%s].", proto, alpn_note);
1404 proxy_ssl_check_peer_ok = FALSE;
1405 }
1406 }
1407 }
1408 #endif
1409
1410 if (proxy_ssl_check_peer_ok == TRUE) {
1411 /* another chance to fail */
1412 post_handshake_rc = ssl_run_proxy_post_handshake(c, filter_ctx->pssl);
1413 }
1414
1415 if (cert) {
1416 X509_free(cert);
1417 }
1418
1419 if (proxy_ssl_check_peer_ok != TRUE
1420 || (post_handshake_rc != OK && post_handshake_rc != DECLINED)) {
1421 /* ensure that the SSL structures etc are freed, etc: */
1422 ssl_filter_io_shutdown(filter_ctx, c, 1);
1423 apr_table_setn(c->notes, "SSL_connect_rv", "err");
1424 return MODSSL_ERROR_BAD_GATEWAY;
1425 }
1426
1427 apr_table_setn(c->notes, "SSL_connect_rv", "ok");
1428 return APR_SUCCESS;
1429 }
1430
1431 /* We rely on SSL_get_error() after the accept, which requires an empty
1432 * error queue before the accept in order to work properly.
1433 */
1434 ERR_clear_error();
1435
1436 if ((n = SSL_accept(filter_ctx->pssl)) <= 0) {
1437 bio_filter_in_ctx_t *inctx = (bio_filter_in_ctx_t *)
1438 BIO_get_data(filter_ctx->pbioRead);
1439 bio_filter_out_ctx_t *outctx = (bio_filter_out_ctx_t *)
1440 BIO_get_data(filter_ctx->pbioWrite);
1441 apr_status_t rc = inctx->rc ? inctx->rc : outctx->rc ;
1442 ssl_err = SSL_get_error(filter_ctx->pssl, n);
1443
1444 if (ssl_err == SSL_ERROR_ZERO_RETURN) {
1445 /*
1446 * The case where the connection was closed before any data
1447 * was transferred. That's not a real error and can occur
1448 * sporadically with some clients.
1449 */
1450 ap_log_cerror(APLOG_MARK, APLOG_INFO, rc, c, APLOGNO(02006)
1451 "SSL handshake stopped: connection was closed");
1452 }
1453 else if (ssl_err == SSL_ERROR_WANT_READ) {
1454 /*
1455 * This is in addition to what was present earlier. It is
1456 * borrowed from openssl_state_machine.c [mod_tls].
1457 * TBD.
1458 */
1459 outctx->rc = APR_EAGAIN;
1460 return APR_EAGAIN;
1461 }
1462 else if (ERR_GET_LIB(ERR_peek_error()) == ERR_LIB_SSL &&
1463 ERR_GET_REASON(ERR_peek_error()) == SSL_R_HTTP_REQUEST) {
1464 /*
1465 * The case where OpenSSL has recognized a HTTP request:
1466 * This means the client speaks plain HTTP on our HTTPS port.
1467 * ssl_io_filter_error will disable the ssl filters when it
1468 * sees this status code.
1469 */
1470 return MODSSL_ERROR_HTTP_ON_HTTPS;
1471 }
1472 else if (ssl_err == SSL_ERROR_SYSCALL) {
1473 ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rc, c, APLOGNO(02007)
1474 "SSL handshake interrupted by system "
1475 "[Hint: Stop button pressed in browser?!]");
1476 }
1477 else /* if (ssl_err == SSL_ERROR_SSL) */ {
1478 /*
1479 * Log SSL errors and any unexpected conditions.
1480 */
1481 ap_log_cerror(APLOG_MARK, APLOG_INFO, rc, c, APLOGNO(02008)
1482 "SSL library error %d in handshake "
1483 "(server %s)", ssl_err,
1484 ssl_util_vhostid(c->pool, server));
1485 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, server);
1486
1487 }
1488 if (inctx->rc == APR_SUCCESS) {
1489 inctx->rc = APR_EGENERAL;
1490 }
1491
1492 ssl_filter_io_shutdown(filter_ctx, c, 1);
1493 return inctx->rc;
1494 }
1495 sc = mySrvConfig(sslconn->server);
1496
1497 /*
1498 * Check for failed client authentication
1499 */
1500 verify_result = SSL_get_verify_result(filter_ctx->pssl);
1501
1502 if ((verify_result != X509_V_OK) ||
1503 sslconn->verify_error)
1504 {
1505 if (ssl_verify_error_is_optional(verify_result) &&
1506 (sc->server->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
1507 {
1508 /* leaving this log message as an error for the moment,
1509 * according to the mod_ssl docs:
1510 * "level optional_no_ca is actually against the idea
1511 * of authentication (but can be used to establish
1512 * SSL test pages, etc.)"
1513 * optional_no_ca doesn't appear to work as advertised
1514 * in 1.x
1515 */
1516 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02009)
1517 "SSL client authentication failed, "
1518 "accepting certificate based on "
1519 "\"SSLVerifyClient optional_no_ca\" "
1520 "configuration");
1521 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, server);
1522 }
1523 else {
1524 const char *error = sslconn->verify_error ?
1525 sslconn->verify_error :
1526 X509_verify_cert_error_string(verify_result);
1527
1528 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02010)
1529 "SSL client authentication failed: %s",
1530 error ? error : "unknown");
1531 ssl_log_ssl_error(SSLLOG_MARK, APLOG_INFO, server);
1532
1533 ssl_filter_io_shutdown(filter_ctx, c, 1);
1534 return APR_ECONNABORTED;
1535 }
1536 }
1537
1538 /*
1539 * Remember the peer certificate's DN
1540 */
1541 if ((cert = SSL_get_peer_certificate(filter_ctx->pssl))) {
1542 if (sslconn->client_cert) {
1543 X509_free(sslconn->client_cert);
1544 }
1545 sslconn->client_cert = cert;
1546 sslconn->client_dn = NULL;
1547 }
1548
1549 /*
1550 * Make really sure that when a peer certificate
1551 * is required we really got one... (be paranoid)
1552 */
1553 if ((sc->server->auth.verify_mode == SSL_CVERIFY_REQUIRE) &&
1554 !sslconn->client_cert)
1555 {
1556 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(02011)
1557 "No acceptable peer certificate available");
1558
1559 ssl_filter_io_shutdown(filter_ctx, c, 1);
1560 return APR_ECONNABORTED;
1561 }
1562
1563 return APR_SUCCESS;
1564 }
1565
ssl_io_filter_input(ap_filter_t * f,apr_bucket_brigade * bb,ap_input_mode_t mode,apr_read_type_e block,apr_off_t readbytes)1566 static apr_status_t ssl_io_filter_input(ap_filter_t *f,
1567 apr_bucket_brigade *bb,
1568 ap_input_mode_t mode,
1569 apr_read_type_e block,
1570 apr_off_t readbytes)
1571 {
1572 apr_status_t status;
1573 bio_filter_in_ctx_t *inctx = f->ctx;
1574 const char *start = inctx->buffer; /* start of block to return */
1575 apr_size_t len = sizeof(inctx->buffer); /* length of block to return */
1576 int is_init = (mode == AP_MODE_INIT);
1577 apr_bucket *bucket;
1578
1579 if (f->c->aborted) {
1580 /* XXX: Ok, if we aborted, we ARE at the EOS. We also have
1581 * aborted. This 'double protection' is probably redundant,
1582 * but also effective against just about anything.
1583 */
1584 bucket = apr_bucket_eos_create(f->c->bucket_alloc);
1585 APR_BRIGADE_INSERT_TAIL(bb, bucket);
1586 return APR_ECONNABORTED;
1587 }
1588
1589 if (!inctx->ssl) {
1590 SSLConnRec *sslconn = myConnConfig(f->c);
1591 if (sslconn->non_ssl_request == NON_SSL_SEND_REQLINE) {
1592 bucket = HTTP_ON_HTTPS_PORT_BUCKET(f->c->bucket_alloc);
1593 APR_BRIGADE_INSERT_TAIL(bb, bucket);
1594 if (mode != AP_MODE_SPECULATIVE) {
1595 sslconn->non_ssl_request = NON_SSL_SEND_HDR_SEP;
1596 }
1597 return APR_SUCCESS;
1598 }
1599 if (sslconn->non_ssl_request == NON_SSL_SEND_HDR_SEP) {
1600 bucket = apr_bucket_immortal_create(CRLF, 2, f->c->bucket_alloc);
1601 APR_BRIGADE_INSERT_TAIL(bb, bucket);
1602 if (mode != AP_MODE_SPECULATIVE) {
1603 sslconn->non_ssl_request = NON_SSL_SET_ERROR_MSG;
1604 }
1605 return APR_SUCCESS;
1606 }
1607 return ap_get_brigade(f->next, bb, mode, block, readbytes);
1608 }
1609
1610 /* XXX: we don't currently support anything other than these modes. */
1611 if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE &&
1612 mode != AP_MODE_SPECULATIVE && mode != AP_MODE_INIT) {
1613 return APR_ENOTIMPL;
1614 }
1615
1616 inctx->mode = mode;
1617 inctx->block = block;
1618
1619 /* XXX: we could actually move ssl_io_filter_handshake to an
1620 * ap_hook_process_connection but would still need to call it for
1621 * AP_MODE_INIT for protocols that may upgrade the connection
1622 * rather than have SSLEngine On configured.
1623 */
1624 if ((status = ssl_io_filter_handshake(inctx->filter_ctx)) != APR_SUCCESS) {
1625 return ssl_io_filter_error(inctx, bb, status, is_init);
1626 }
1627
1628 if (is_init) {
1629 /* protocol module needs to handshake before sending
1630 * data to client (e.g. NNTP or FTP)
1631 */
1632 return APR_SUCCESS;
1633 }
1634
1635 if (inctx->mode == AP_MODE_READBYTES ||
1636 inctx->mode == AP_MODE_SPECULATIVE) {
1637 /* Protected from truncation, readbytes < MAX_SIZE_T
1638 * FIXME: No, it's *not* protected. -- jre */
1639 if (readbytes < len) {
1640 len = (apr_size_t)readbytes;
1641 }
1642 status = ssl_io_input_read(inctx, inctx->buffer, &len);
1643 }
1644 else if (inctx->mode == AP_MODE_GETLINE) {
1645 const char *pos;
1646
1647 /* Satisfy the read directly out of the buffer if possible;
1648 * invoking ssl_io_input_getline will mean the entire buffer
1649 * is copied once (unnecessarily) for each GETLINE call. */
1650 if (inctx->cbuf.length
1651 && (pos = memchr(inctx->cbuf.value, APR_ASCII_LF,
1652 inctx->cbuf.length)) != NULL) {
1653 start = inctx->cbuf.value;
1654 len = 1 + pos - start; /* +1 to include LF */
1655 /* Buffer contents now consumed. */
1656 inctx->cbuf.value += len;
1657 inctx->cbuf.length -= len;
1658 status = APR_SUCCESS;
1659 }
1660 else {
1661 /* Otherwise fall back to the hard way. */
1662 status = ssl_io_input_getline(inctx, inctx->buffer, &len);
1663 }
1664 }
1665 else {
1666 /* We have no idea what you are talking about, so return an error. */
1667 status = APR_ENOTIMPL;
1668 }
1669
1670 /* It is possible for mod_ssl's BIO to be used outside of the
1671 * direct control of mod_ssl's input or output filter -- notably,
1672 * when mod_ssl initiates a renegotiation. Switching the BIO mode
1673 * back to "blocking" here ensures such operations don't fail with
1674 * SSL_ERROR_WANT_READ. */
1675 inctx->block = APR_BLOCK_READ;
1676
1677 /* Handle custom errors. */
1678 if (status != APR_SUCCESS) {
1679 return ssl_io_filter_error(inctx, bb, status, 0);
1680 }
1681
1682 /* Create a transient bucket out of the decrypted data. */
1683 if (len > 0) {
1684 bucket =
1685 apr_bucket_transient_create(start, len, f->c->bucket_alloc);
1686 APR_BRIGADE_INSERT_TAIL(bb, bucket);
1687 }
1688
1689 return APR_SUCCESS;
1690 }
1691
1692
1693 /* ssl_io_filter_output() produces one SSL/TLS record per bucket
1694 * passed down the output filter stack. This results in a high
1695 * overhead (more network packets & TLS processing) for any output
1696 * comprising many small buckets. SSI output passed through the HTTP
1697 * chunk filter, for example, may produce many brigades containing
1698 * small buckets - [chunk-size CRLF] [chunk-data] [CRLF].
1699 *
1700 * Sending HTTP response headers as a separate TLS record to the
1701 * response body also reveals information to a network observer (the
1702 * size of headers) which can be significant.
1703 *
1704 * The coalescing filter merges data buckets with the aim of producing
1705 * fewer, larger TLS records - without copying/buffering all content
1706 * and introducing unnecessary overhead.
1707 *
1708 * ### This buffering could be probably be done more comprehensively
1709 * ### in ssl_io_filter_output itself.
1710 *
1711 * ### Another possible performance optimisation in particular for the
1712 * ### [HEAP] [FILE] HTTP response case is using a brigade rather than
1713 * ### a char array to buffer; using apr_brigade_write() to append
1714 * ### will use already-allocated memory from the HEAP, reducing # of
1715 * ### copies.
1716 */
1717
1718 #define COALESCE_BYTES (AP_IOBUFSIZE)
1719
1720 struct coalesce_ctx {
1721 char buffer[COALESCE_BYTES];
1722 apr_size_t bytes; /* number of bytes of buffer used. */
1723 };
1724
ssl_io_filter_coalesce(ap_filter_t * f,apr_bucket_brigade * bb)1725 static apr_status_t ssl_io_filter_coalesce(ap_filter_t *f,
1726 apr_bucket_brigade *bb)
1727 {
1728 apr_bucket *e, *upto;
1729 apr_size_t bytes = 0;
1730 struct coalesce_ctx *ctx = f->ctx;
1731 apr_size_t buffered = ctx ? ctx->bytes : 0; /* space used on entry */
1732 unsigned count = 0;
1733
1734 /* The brigade consists of zero-or-more small data buckets which
1735 * can be coalesced (referred to as the "prefix"), followed by the
1736 * remainder of the brigade.
1737 *
1738 * Find the last bucket - if any - of that prefix. count gives
1739 * the number of buckets in the prefix. The "prefix" must contain
1740 * only data buckets with known length, and must be of a total
1741 * size which fits into the buffer.
1742 *
1743 * N.B.: The process here could be repeated throughout the brigade
1744 * (coalesce any run of consecutive data buckets) but this would
1745 * add significant complexity, particularly to memory
1746 * management. */
1747 for (e = APR_BRIGADE_FIRST(bb);
1748 e != APR_BRIGADE_SENTINEL(bb)
1749 && !APR_BUCKET_IS_METADATA(e)
1750 && e->length != (apr_size_t)-1
1751 && e->length <= COALESCE_BYTES
1752 && (buffered + bytes + e->length) <= COALESCE_BYTES;
1753 e = APR_BUCKET_NEXT(e)) {
1754 /* don't count zero-length buckets */
1755 if (e->length) {
1756 bytes += e->length;
1757 count++;
1758 }
1759 }
1760
1761 /* If there is room remaining and the next bucket is a data
1762 * bucket, try to include it in the prefix to coalesce. For a
1763 * typical [HEAP] [FILE] HTTP response brigade, this handles
1764 * merging the headers and the start of the body into a single TLS
1765 * record. */
1766 if (bytes + buffered > 0
1767 && bytes + buffered < COALESCE_BYTES
1768 && e != APR_BRIGADE_SENTINEL(bb)
1769 && !APR_BUCKET_IS_METADATA(e)) {
1770 apr_status_t rv = APR_SUCCESS;
1771
1772 /* For an indeterminate length bucket (PIPE/CGI/...), try a
1773 * non-blocking read to have it morph into a HEAP. If the
1774 * read fails with EAGAIN, it is harmless to try a split
1775 * anyway, split is ENOTIMPL for most PIPE-like buckets. */
1776 if (e->length == (apr_size_t)-1) {
1777 const char *discard;
1778 apr_size_t ignore;
1779
1780 rv = apr_bucket_read(e, &discard, &ignore, APR_NONBLOCK_READ);
1781 if (rv != APR_SUCCESS && !APR_STATUS_IS_EAGAIN(rv)) {
1782 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, f->c, APLOGNO(10232)
1783 "coalesce failed to read from %s bucket",
1784 e->type->name);
1785 return AP_FILTER_ERROR;
1786 }
1787 }
1788
1789 if (rv == APR_SUCCESS) {
1790 /* If the read above made the bucket morph, it may now fit
1791 * entirely within the buffer. Otherwise, split it so it does
1792 * fit. */
1793 if (e->length > COALESCE_BYTES
1794 || e->length + buffered + bytes > COALESCE_BYTES) {
1795 rv = apr_bucket_split(e, COALESCE_BYTES - (buffered + bytes));
1796 }
1797
1798 if (rv == APR_SUCCESS && e->length == 0) {
1799 /* As above, don't count in the prefix if the bucket is
1800 * now zero-length. */
1801 }
1802 else if (rv == APR_SUCCESS) {
1803 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, f->c,
1804 "coalesce: adding %" APR_SIZE_T_FMT " bytes "
1805 "from split %s bucket, total %" APR_SIZE_T_FMT,
1806 e->length, e->type->name, bytes + buffered);
1807
1808 count++;
1809 bytes += e->length;
1810 e = APR_BUCKET_NEXT(e);
1811 }
1812 else if (rv != APR_ENOTIMPL) {
1813 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, f->c, APLOGNO(10233)
1814 "coalesce: failed to split data bucket");
1815 return AP_FILTER_ERROR;
1816 }
1817 }
1818 }
1819
1820 /* The prefix is zero or more buckets. upto now points to the
1821 * bucket AFTER the end of the prefix, which may be the brigade
1822 * sentinel. */
1823 upto = e;
1824
1825 /* Coalesce the prefix, if any of the following are true:
1826 *
1827 * a) the prefix is more than one bucket
1828 * OR
1829 * b) the prefix is the entire brigade, which is a single bucket
1830 * AND the prefix length is smaller than the buffer size,
1831 * OR
1832 * c) the prefix is a single bucket
1833 * AND there is buffered data from a previous pass.
1834 *
1835 * The aim with (b) is to buffer a small bucket so it can be
1836 * coalesced with future invocations of this filter. e.g. three
1837 * calls each with a single 100 byte HEAP bucket should get
1838 * coalesced together. But an invocation with a 8192 byte HEAP
1839 * should pass through untouched.
1840 */
1841 if (bytes > 0
1842 && (count > 1
1843 || (upto == APR_BRIGADE_SENTINEL(bb)
1844 && bytes < COALESCE_BYTES)
1845 || (ctx && ctx->bytes > 0))) {
1846 /* If coalescing some bytes, ensure a context has been
1847 * created. */
1848 if (!ctx) {
1849 f->ctx = ctx = apr_palloc(f->c->pool, sizeof *ctx);
1850 ctx->bytes = 0;
1851 }
1852
1853 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, f->c,
1854 "coalesce: have %" APR_SIZE_T_FMT " bytes, "
1855 "adding %" APR_SIZE_T_FMT " more (buckets=%u)",
1856 ctx->bytes, bytes, count);
1857
1858 /* Iterate through the prefix segment. For non-fatal errors
1859 * in this loop it is safe to break out and fall back to the
1860 * normal path of sending the buffer + remaining buckets in
1861 * brigade. */
1862 e = APR_BRIGADE_FIRST(bb);
1863 while (e != upto) {
1864 apr_size_t len;
1865 const char *data;
1866 apr_bucket *next;
1867
1868 if (APR_BUCKET_IS_METADATA(e)
1869 || e->length == (apr_size_t)-1) {
1870 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, f->c, APLOGNO(02012)
1871 "unexpected %s bucket during coalesce",
1872 e->type->name);
1873 break; /* non-fatal error; break out */
1874 }
1875
1876 if (e->length) {
1877 apr_status_t rv;
1878
1879 /* A blocking read should be fine here for a
1880 * known-length data bucket, rather than the usual
1881 * non-block/flush/block. */
1882 rv = apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1883 if (rv) {
1884 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, f->c, APLOGNO(02013)
1885 "coalesce failed to read from data bucket");
1886 return AP_FILTER_ERROR;
1887 }
1888
1889 /* Be paranoid. */
1890 if (len > sizeof ctx->buffer
1891 || (len + ctx->bytes > sizeof ctx->buffer)) {
1892 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, f->c, APLOGNO(02014)
1893 "unexpected coalesced bucket data length");
1894 break; /* non-fatal error; break out */
1895 }
1896
1897 memcpy(ctx->buffer + ctx->bytes, data, len);
1898 ctx->bytes += len;
1899 }
1900
1901 next = APR_BUCKET_NEXT(e);
1902 apr_bucket_delete(e);
1903 e = next;
1904 }
1905 }
1906
1907 if (APR_BRIGADE_EMPTY(bb)) {
1908 /* If the brigade is now empty, our work here is done. */
1909 return APR_SUCCESS;
1910 }
1911
1912 /* If anything remains in the brigade, it must now be passed down
1913 * the filter stack, first prepending anything that has been
1914 * coalesced. */
1915 if (ctx && ctx->bytes) {
1916 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, f->c,
1917 "coalesce: passing on %" APR_SIZE_T_FMT " bytes", ctx->bytes);
1918
1919 e = apr_bucket_transient_create(ctx->buffer, ctx->bytes, bb->bucket_alloc);
1920 APR_BRIGADE_INSERT_HEAD(bb, e);
1921 ctx->bytes = 0; /* buffer now emptied. */
1922 }
1923
1924 return ap_pass_brigade(f->next, bb);
1925 }
1926
ssl_io_filter_output(ap_filter_t * f,apr_bucket_brigade * bb)1927 static apr_status_t ssl_io_filter_output(ap_filter_t *f,
1928 apr_bucket_brigade *bb)
1929 {
1930 apr_status_t status = APR_SUCCESS;
1931 ssl_filter_ctx_t *filter_ctx = f->ctx;
1932 bio_filter_in_ctx_t *inctx;
1933 bio_filter_out_ctx_t *outctx;
1934 apr_read_type_e rblock = APR_NONBLOCK_READ;
1935
1936 if (f->c->aborted) {
1937 apr_brigade_cleanup(bb);
1938 return APR_ECONNABORTED;
1939 }
1940
1941 if (!filter_ctx->pssl) {
1942 /* ssl_filter_io_shutdown was called */
1943 return ap_pass_brigade(f->next, bb);
1944 }
1945
1946 inctx = (bio_filter_in_ctx_t *)BIO_get_data(filter_ctx->pbioRead);
1947 outctx = (bio_filter_out_ctx_t *)BIO_get_data(filter_ctx->pbioWrite);
1948
1949 /* When we are the writer, we must initialize the inctx
1950 * mode so that we block for any required ssl input, because
1951 * output filtering is always nonblocking.
1952 */
1953 inctx->mode = AP_MODE_READBYTES;
1954 inctx->block = APR_BLOCK_READ;
1955
1956 if ((status = ssl_io_filter_handshake(filter_ctx)) != APR_SUCCESS) {
1957 return ssl_io_filter_error(inctx, bb, status, 0);
1958 }
1959
1960 while (!APR_BRIGADE_EMPTY(bb) && status == APR_SUCCESS) {
1961 apr_bucket *bucket = APR_BRIGADE_FIRST(bb);
1962
1963 if (APR_BUCKET_IS_METADATA(bucket)) {
1964 /* Pass through metadata buckets untouched. EOC is
1965 * special; terminate the SSL layer first. */
1966 if (AP_BUCKET_IS_EOC(bucket)) {
1967 ssl_filter_io_shutdown(filter_ctx, f->c, 0);
1968 }
1969 AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(outctx->bb));
1970
1971 /* Metadata buckets are passed one per brigade; it might
1972 * be more efficient (but also more complex) to use
1973 * outctx->bb as a true buffer and interleave these with
1974 * data buckets. */
1975 APR_BUCKET_REMOVE(bucket);
1976 APR_BRIGADE_INSERT_HEAD(outctx->bb, bucket);
1977 status = ap_pass_brigade(f->next, outctx->bb);
1978 if (status == APR_SUCCESS && f->c->aborted)
1979 status = APR_ECONNRESET;
1980 apr_brigade_cleanup(outctx->bb);
1981 }
1982 else {
1983 /* Filter a data bucket. */
1984 const char *data;
1985 apr_size_t len;
1986
1987 status = apr_bucket_read(bucket, &data, &len, rblock);
1988
1989 if (APR_STATUS_IS_EAGAIN(status)) {
1990 /* No data available: flush... */
1991 if (bio_filter_out_flush(filter_ctx->pbioWrite) < 0) {
1992 status = outctx->rc;
1993 break;
1994 }
1995 rblock = APR_BLOCK_READ;
1996 /* and try again with a blocking read. */
1997 status = APR_SUCCESS;
1998 continue;
1999 }
2000
2001 rblock = APR_NONBLOCK_READ;
2002
2003 if (!APR_STATUS_IS_EOF(status) && (status != APR_SUCCESS)) {
2004 break;
2005 }
2006
2007 status = ssl_filter_write(f, data, len);
2008 apr_bucket_delete(bucket);
2009 }
2010
2011 }
2012
2013 return status;
2014 }
2015
2016 struct modssl_buffer_ctx {
2017 apr_bucket_brigade *bb;
2018 };
2019
ssl_io_buffer_fill(request_rec * r,apr_size_t maxlen)2020 int ssl_io_buffer_fill(request_rec *r, apr_size_t maxlen)
2021 {
2022 conn_rec *c = r->connection;
2023 struct modssl_buffer_ctx *ctx;
2024 apr_bucket_brigade *tempb;
2025 apr_off_t total = 0; /* total length buffered */
2026 int eos = 0; /* non-zero once EOS is seen */
2027
2028 /* Create the context which will be passed to the input filter;
2029 * containing a setaside pool and a brigade which constrain the
2030 * lifetime of the buffered data. */
2031 ctx = apr_palloc(r->pool, sizeof *ctx);
2032 ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
2033
2034 /* ... and a temporary brigade. */
2035 tempb = apr_brigade_create(r->pool, c->bucket_alloc);
2036
2037 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, c, "filling buffer, max size "
2038 "%" APR_SIZE_T_FMT " bytes", maxlen);
2039
2040 do {
2041 apr_status_t rv;
2042 apr_bucket *e, *next;
2043
2044 /* The request body is read from the protocol-level input
2045 * filters; the buffering filter will reinject it from that
2046 * level, allowing content/resource filters to run later, if
2047 * necessary. */
2048
2049 rv = ap_get_brigade(r->proto_input_filters, tempb, AP_MODE_READBYTES,
2050 APR_BLOCK_READ, 8192);
2051 if (rv) {
2052 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(02015)
2053 "could not read request body for SSL buffer");
2054 return ap_map_http_request_error(rv, HTTP_INTERNAL_SERVER_ERROR);
2055 }
2056
2057 /* Iterate through the returned brigade: setaside each bucket
2058 * into the context's pool and move it into the brigade. */
2059 for (e = APR_BRIGADE_FIRST(tempb);
2060 e != APR_BRIGADE_SENTINEL(tempb) && !eos; e = next) {
2061 const char *data;
2062 apr_size_t len;
2063
2064 next = APR_BUCKET_NEXT(e);
2065
2066 if (APR_BUCKET_IS_EOS(e)) {
2067 eos = 1;
2068 } else if (!APR_BUCKET_IS_METADATA(e)) {
2069 rv = apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
2070 if (rv != APR_SUCCESS) {
2071 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(02016)
2072 "could not read bucket for SSL buffer");
2073 return HTTP_INTERNAL_SERVER_ERROR;
2074 }
2075 total += len;
2076 }
2077
2078 rv = apr_bucket_setaside(e, r->pool);
2079 if (rv != APR_SUCCESS) {
2080 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(02017)
2081 "could not setaside bucket for SSL buffer");
2082 return HTTP_INTERNAL_SERVER_ERROR;
2083 }
2084
2085 APR_BUCKET_REMOVE(e);
2086 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
2087 }
2088
2089 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, c,
2090 "total of %" APR_OFF_T_FMT " bytes in buffer, eos=%d",
2091 total, eos);
2092
2093 /* Fail if this exceeds the maximum buffer size. */
2094 if (total > maxlen) {
2095 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02018)
2096 "request body exceeds maximum size (%" APR_SIZE_T_FMT
2097 ") for SSL buffer", maxlen);
2098 return HTTP_REQUEST_ENTITY_TOO_LARGE;
2099 }
2100
2101 } while (!eos);
2102
2103 apr_brigade_destroy(tempb);
2104
2105 /* After consuming all protocol-level input, remove all protocol-level
2106 * filters. It should strictly only be necessary to remove filters
2107 * at exactly ftype == AP_FTYPE_PROTOCOL, since this filter will
2108 * precede all > AP_FTYPE_PROTOCOL anyway. */
2109 while (r->proto_input_filters->frec->ftype < AP_FTYPE_CONNECTION) {
2110 ap_remove_input_filter(r->proto_input_filters);
2111 }
2112
2113 /* Insert the filter which will supply the buffered content. */
2114 ap_add_input_filter(ssl_io_buffer, ctx, r, c);
2115
2116 return 0;
2117 }
2118
2119 /* This input filter supplies the buffered request body to the caller
2120 * from the brigade stored in f->ctx. Note that the placement of this
2121 * filter in the filter stack is important; it must be the first
2122 * r->proto_input_filter; lower-typed filters will not be preserved
2123 * across internal redirects (see PR 43738). */
ssl_io_filter_buffer(ap_filter_t * f,apr_bucket_brigade * bb,ap_input_mode_t mode,apr_read_type_e block,apr_off_t bytes)2124 static apr_status_t ssl_io_filter_buffer(ap_filter_t *f,
2125 apr_bucket_brigade *bb,
2126 ap_input_mode_t mode,
2127 apr_read_type_e block,
2128 apr_off_t bytes)
2129 {
2130 struct modssl_buffer_ctx *ctx = f->ctx;
2131 apr_status_t rv;
2132 apr_bucket *e, *d;
2133
2134 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, f->c,
2135 "read from buffered SSL brigade, mode %d, "
2136 "%" APR_OFF_T_FMT " bytes",
2137 mode, bytes);
2138
2139 if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) {
2140 return APR_ENOTIMPL;
2141 }
2142
2143 if (APR_BRIGADE_EMPTY(ctx->bb)) {
2144 /* Surprisingly (and perhaps, wrongly), the request body can be
2145 * pulled from the input filter stack more than once; a
2146 * handler may read it, and ap_discard_request_body() will
2147 * attempt to do so again after *every* request. So input
2148 * filters must be prepared to give up an EOS if invoked after
2149 * initially reading the request. The HTTP_IN filter does this
2150 * with its ->eos_sent flag. */
2151
2152 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_eos_create(f->c->bucket_alloc));
2153 return APR_SUCCESS;
2154 }
2155
2156 if (mode == AP_MODE_READBYTES) {
2157 /* Partition the buffered brigade. */
2158 rv = apr_brigade_partition(ctx->bb, bytes, &e);
2159 if (rv && rv != APR_INCOMPLETE) {
2160 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, f->c, APLOGNO(02019)
2161 "could not partition buffered SSL brigade");
2162 ap_remove_input_filter(f);
2163 return rv;
2164 }
2165
2166 /* If the buffered brigade contains less then the requested
2167 * length, just pass it all back. */
2168 if (rv == APR_INCOMPLETE) {
2169 APR_BRIGADE_CONCAT(bb, ctx->bb);
2170 } else {
2171 d = APR_BRIGADE_FIRST(ctx->bb);
2172
2173 e = APR_BUCKET_PREV(e);
2174
2175 /* Unsplice the partitioned segment and move it into the
2176 * passed-in brigade; no convenient way to do this with
2177 * the APR_BRIGADE_* macros. */
2178 APR_RING_UNSPLICE(d, e, link);
2179 APR_RING_SPLICE_HEAD(&bb->list, d, e, apr_bucket, link);
2180
2181 APR_BRIGADE_CHECK_CONSISTENCY(bb);
2182 APR_BRIGADE_CHECK_CONSISTENCY(ctx->bb);
2183 }
2184 }
2185 else {
2186 /* Split a line into the passed-in brigade. */
2187 rv = apr_brigade_split_line(bb, ctx->bb, block, bytes);
2188
2189 if (rv) {
2190 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, f->c, APLOGNO(02020)
2191 "could not split line from buffered SSL brigade");
2192 ap_remove_input_filter(f);
2193 return rv;
2194 }
2195 }
2196
2197 if (APR_BRIGADE_EMPTY(ctx->bb)) {
2198 e = APR_BRIGADE_LAST(bb);
2199
2200 /* Ensure that the brigade is terminated by an EOS if the
2201 * buffered request body has been entirely consumed. */
2202 if (e == APR_BRIGADE_SENTINEL(bb) || !APR_BUCKET_IS_EOS(e)) {
2203 e = apr_bucket_eos_create(f->c->bucket_alloc);
2204 APR_BRIGADE_INSERT_TAIL(bb, e);
2205 }
2206
2207 ap_log_cerror(APLOG_MARK, APLOG_TRACE4, 0, f->c,
2208 "buffered SSL brigade exhausted");
2209 /* Note that the filter must *not* be removed here; it may be
2210 * invoked again, see comment above. */
2211 }
2212
2213 return APR_SUCCESS;
2214 }
2215
2216 /* The request_rec pointer is passed in here only to ensure that the
2217 * filter chain is modified correctly when doing a TLS upgrade. It
2218 * must *not* be used otherwise. */
ssl_io_input_add_filter(ssl_filter_ctx_t * filter_ctx,conn_rec * c,request_rec * r,SSL * ssl)2219 static void ssl_io_input_add_filter(ssl_filter_ctx_t *filter_ctx, conn_rec *c,
2220 request_rec *r, SSL *ssl)
2221 {
2222 bio_filter_in_ctx_t *inctx;
2223
2224 inctx = apr_palloc(c->pool, sizeof(*inctx));
2225
2226 filter_ctx->pInputFilter = ap_add_input_filter(ssl_io_filter, inctx, r, c);
2227
2228 #if MODSSL_USE_OPENSSL_PRE_1_1_API
2229 filter_ctx->pbioRead = BIO_new(&bio_filter_in_method);
2230 #else
2231 filter_ctx->pbioRead = BIO_new(bio_filter_in_method);
2232 #endif
2233 BIO_set_data(filter_ctx->pbioRead, (void *)inctx);
2234
2235 inctx->ssl = ssl;
2236 inctx->bio_out = filter_ctx->pbioWrite;
2237 inctx->f = filter_ctx->pInputFilter;
2238 inctx->rc = APR_SUCCESS;
2239 inctx->mode = AP_MODE_READBYTES;
2240 inctx->cbuf.length = 0;
2241 inctx->bb = apr_brigade_create(c->pool, c->bucket_alloc);
2242 inctx->block = APR_BLOCK_READ;
2243 inctx->pool = c->pool;
2244 inctx->filter_ctx = filter_ctx;
2245 }
2246
2247 /* The request_rec pointer is passed in here only to ensure that the
2248 * filter chain is modified correctly when doing a TLS upgrade. It
2249 * must *not* be used otherwise. */
ssl_io_filter_init(conn_rec * c,request_rec * r,SSL * ssl)2250 void ssl_io_filter_init(conn_rec *c, request_rec *r, SSL *ssl)
2251 {
2252 ssl_filter_ctx_t *filter_ctx;
2253
2254 filter_ctx = apr_palloc(c->pool, sizeof(ssl_filter_ctx_t));
2255
2256 filter_ctx->config = myConnConfig(c);
2257
2258 ap_add_output_filter(ssl_io_coalesce, NULL, r, c);
2259
2260 filter_ctx->pOutputFilter = ap_add_output_filter(ssl_io_filter,
2261 filter_ctx, r, c);
2262
2263 #if MODSSL_USE_OPENSSL_PRE_1_1_API
2264 filter_ctx->pbioWrite = BIO_new(&bio_filter_out_method);
2265 #else
2266 filter_ctx->pbioWrite = BIO_new(bio_filter_out_method);
2267 #endif
2268 BIO_set_data(filter_ctx->pbioWrite, (void *)bio_filter_out_ctx_new(filter_ctx, c));
2269
2270 /* write is non blocking for the benefit of async mpm */
2271 if (c->cs) {
2272 BIO_set_nbio(filter_ctx->pbioWrite, 1);
2273 ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, c,
2274 "Enabling non-blocking writes");
2275 }
2276
2277 ssl_io_input_add_filter(filter_ctx, c, r, ssl);
2278
2279 SSL_set_bio(ssl, filter_ctx->pbioRead, filter_ctx->pbioWrite);
2280 filter_ctx->pssl = ssl;
2281
2282 apr_pool_cleanup_register(c->pool, (void*)filter_ctx,
2283 ssl_io_filter_cleanup, apr_pool_cleanup_null);
2284
2285 if (APLOG_CS_IS_LEVEL(c, mySrvFromConn(c), APLOG_TRACE4)) {
2286 BIO *rbio = SSL_get_rbio(ssl),
2287 *wbio = SSL_get_wbio(ssl);
2288 BIO_set_callback(rbio, ssl_io_data_cb);
2289 BIO_set_callback_arg(rbio, (void *)ssl);
2290 if (wbio && wbio != rbio) {
2291 BIO_set_callback(wbio, ssl_io_data_cb);
2292 BIO_set_callback_arg(wbio, (void *)ssl);
2293 }
2294 }
2295
2296 return;
2297 }
2298
ssl_io_filter_register(apr_pool_t * p)2299 void ssl_io_filter_register(apr_pool_t *p)
2300 {
2301 ap_register_input_filter (ssl_io_filter, ssl_io_filter_input, NULL, AP_FTYPE_CONNECTION + 5);
2302 ap_register_output_filter (ssl_io_coalesce, ssl_io_filter_coalesce, NULL, AP_FTYPE_CONNECTION + 4);
2303 ap_register_output_filter (ssl_io_filter, ssl_io_filter_output, NULL, AP_FTYPE_CONNECTION + 5);
2304
2305 ap_register_input_filter (ssl_io_buffer, ssl_io_filter_buffer, NULL, AP_FTYPE_PROTOCOL);
2306
2307 return;
2308 }
2309
2310 /* _________________________________________________________________
2311 **
2312 ** I/O Data Debugging
2313 ** _________________________________________________________________
2314 */
2315
2316 #define DUMP_WIDTH 16
2317
ssl_io_data_dump(conn_rec * c,server_rec * s,const char * b,long len)2318 static void ssl_io_data_dump(conn_rec *c, server_rec *s,
2319 const char *b, long len)
2320 {
2321 char buf[256];
2322 int i, j, rows, trunc, pos;
2323 unsigned char ch;
2324
2325 trunc = 0;
2326 for (; (len > 0) && ((b[len-1] == ' ') || (b[len-1] == '\0')); len--)
2327 trunc++;
2328 rows = (len / DUMP_WIDTH);
2329 if ((rows * DUMP_WIDTH) < len)
2330 rows++;
2331 ap_log_cserror(APLOG_MARK, APLOG_TRACE7, 0, c, s,
2332 "+-------------------------------------------------------------------------+");
2333 for (i = 0 ; i < rows; i++) {
2334 #if APR_CHARSET_EBCDIC
2335 char ebcdic_text[DUMP_WIDTH];
2336 j = DUMP_WIDTH;
2337 if ((i * DUMP_WIDTH + j) > len)
2338 j = len % DUMP_WIDTH;
2339 if (j == 0)
2340 j = DUMP_WIDTH;
2341 memcpy(ebcdic_text,(char *)(b) + i * DUMP_WIDTH, j);
2342 ap_xlate_proto_from_ascii(ebcdic_text, j);
2343 #endif /* APR_CHARSET_EBCDIC */
2344 pos = 0;
2345 pos += apr_snprintf(buf, sizeof(buf)-pos, "| %04x: ", i * DUMP_WIDTH);
2346 for (j = 0; j < DUMP_WIDTH; j++) {
2347 if (((i * DUMP_WIDTH) + j) >= len)
2348 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, " ");
2349 else {
2350 ch = ((unsigned char)*((char *)(b) + i * DUMP_WIDTH + j)) & 0xff;
2351 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, "%02x%c", ch , j==7 ? '-' : ' ');
2352 }
2353 }
2354 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, " ");
2355 for (j = 0; j < DUMP_WIDTH; j++) {
2356 if (((i * DUMP_WIDTH) + j) >= len)
2357 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, " ");
2358 else {
2359 ch = ((unsigned char)*((char *)(b) + i * DUMP_WIDTH + j)) & 0xff;
2360 #if APR_CHARSET_EBCDIC
2361 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, "%c", (ch >= 0x20 && ch <= 0x7F) ? ebcdic_text[j] : '.');
2362 #else /* APR_CHARSET_EBCDIC */
2363 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, "%c", ((ch >= ' ') && (ch <= '~')) ? ch : '.');
2364 #endif /* APR_CHARSET_EBCDIC */
2365 }
2366 }
2367 pos += apr_snprintf(buf+pos, sizeof(buf)-pos, " |");
2368 ap_log_cserror(APLOG_MARK, APLOG_TRACE7, 0, c, s, "%s", buf);
2369 }
2370 if (trunc > 0)
2371 ap_log_cserror(APLOG_MARK, APLOG_TRACE7, 0, c, s,
2372 "| %04ld - <SPACES/NULS>", len + trunc);
2373 ap_log_cserror(APLOG_MARK, APLOG_TRACE7, 0, c, s,
2374 "+-------------------------------------------------------------------------+");
2375 }
2376
ssl_io_data_cb(BIO * bio,int cmd,const char * argp,int argi,long argl,long rc)2377 long ssl_io_data_cb(BIO *bio, int cmd,
2378 const char *argp,
2379 int argi, long argl, long rc)
2380 {
2381 SSL *ssl;
2382 conn_rec *c;
2383 server_rec *s;
2384
2385 if ((ssl = (SSL *)BIO_get_callback_arg(bio)) == NULL)
2386 return rc;
2387 if ((c = (conn_rec *)SSL_get_app_data(ssl)) == NULL)
2388 return rc;
2389 s = mySrvFromConn(c);
2390
2391 if ( cmd == (BIO_CB_WRITE|BIO_CB_RETURN)
2392 || cmd == (BIO_CB_READ |BIO_CB_RETURN) ) {
2393 if (rc >= 0) {
2394 const char *dump = "";
2395 if (APLOG_CS_IS_LEVEL(c, s, APLOG_TRACE7)) {
2396 if (argp != NULL)
2397 dump = "(BIO dump follows)";
2398 else
2399 dump = "(Oops, no memory buffer?)";
2400 }
2401 ap_log_cserror(APLOG_MARK, APLOG_TRACE4, 0, c, s,
2402 "%s: %s %ld/%d bytes %s BIO#%pp [mem: %pp] %s",
2403 MODSSL_LIBRARY_NAME,
2404 (cmd == (BIO_CB_WRITE|BIO_CB_RETURN) ? "write" : "read"),
2405 rc, argi, (cmd == (BIO_CB_WRITE|BIO_CB_RETURN) ? "to" : "from"),
2406 bio, argp, dump);
2407 if (*dump != '\0' && argp != NULL)
2408 ssl_io_data_dump(c, s, argp, rc);
2409 }
2410 else {
2411 ap_log_cserror(APLOG_MARK, APLOG_TRACE4, 0, c, s,
2412 "%s: I/O error, %d bytes expected to %s on BIO#%pp [mem: %pp]",
2413 MODSSL_LIBRARY_NAME, argi,
2414 (cmd == (BIO_CB_WRITE|BIO_CB_RETURN) ? "write" : "read"),
2415 bio, argp);
2416 }
2417 }
2418 return rc;
2419 }
2420