diff --git a/docs/log-message-tags/next-number b/docs/log-message-tags/next-number index 5292663bca9..76c0264a855 100644 --- a/docs/log-message-tags/next-number +++ b/docs/log-message-tags/next-number @@ -1 +1 @@ -10709 +10710 \ No newline at end of file diff --git a/modules/filters/mod_crypto.c b/modules/filters/mod_crypto.c index 9829c8b1b71..2c9c2e8f2c5 100644 --- a/modules/filters/mod_crypto.c +++ b/modules/filters/mod_crypto.c @@ -105,6 +105,8 @@ typedef struct crypto_ctx apr_crypto_block_key_mode_t *mode; apr_crypto_block_t *block; const unsigned char *iv; + unsigned char *ivbuf; + apr_size_t ivlen; apr_off_t remaining; apr_off_t written; apr_size_t osize; @@ -589,19 +591,30 @@ static int init_decrypt(ap_filter_t * f) } /** - * Run the crypto algorithm, write to ctx->out + * Run the crypto algorithm on in, appending the output to ctx->out. + * + * ctx->remaining counts the input bytes still to be consumed in this + * round, so a round ends on a fixed input boundary regardless of how + * much output the cipher has produced or is holding back. ctx->written + * counts the output bytes present in ctx->out. */ static apr_status_t do_crypto(ap_filter_t * f, unsigned char *in, apr_off_t size, int finish) { apr_status_t rv; crypto_ctx *ctx = f->ctx; - apr_off_t extra = 0; apr_size_t blockSize = 0; int need_iv = (ctx->iv == NULL); unsigned char *out; apr_size_t written; + if (!ctx->out) { + ctx->out = apr_palloc(f->r->pool, + ctx->osize + ctx->cipher->blocksize); + apr_crypto_clear(f->r->pool, ctx->out, + ctx->osize + ctx->cipher->blocksize); + } + /* encrypt the given buffer */ if (ctx->encrypt) { @@ -614,32 +627,73 @@ do_crypto(ap_filter_t * f, unsigned char *in, apr_off_t size, int finish) APLOGNO(03421) "could not initialise encryption"); return rv; } - } - - if (!ctx->out) { + /* no precomputed iv? send the generated iv as the first block + * of the stream, ahead of anything the cipher produces */ if (need_iv && ctx->iv) { - ctx->osize += blockSize; + rv = apr_brigade_write(ctx->bb, NULL, NULL, + (const char *) ctx->iv, blockSize); + if (APR_SUCCESS != rv) { + return rv; + } } + } - out = ctx->out = apr_palloc(f->r->pool, - ctx->osize + ctx->cipher->blocksize); - apr_crypto_clear(f->r->pool, ctx->out, - ctx->osize + ctx->cipher->blocksize); + } - /* no precomputed iv? write the generated iv as the first block of the stream */ - if (need_iv && ctx->iv) { - memcpy(out, ctx->iv, blockSize); - ctx->remaining += blockSize; - out += blockSize; - extra = blockSize; - } + /* decrypt the given buffer */ + else { + + /* no precomputed iv? the first block in the stream is the iv */ + if (need_iv) { + apr_size_t want = ctx->cipher->blocksize - ctx->ivlen; + if (!ctx->ivbuf) { + ctx->ivbuf = apr_palloc(f->r->pool, ctx->cipher->blocksize); + } + if (want > (apr_size_t) size) { + want = (apr_size_t) size; + } + if (want) { + memcpy(ctx->ivbuf + ctx->ivlen, in, want); + ctx->ivlen += want; + ctx->remaining -= want; + in += want; + size -= want; + } + if (ctx->ivlen < ctx->cipher->blocksize) { + if (finish) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r, APLOGNO(10709) + "crypto: stream ended before a full iv was read"); + return APR_EINCOMPLETE; + } + return APR_SUCCESS; + } + ctx->iv = ctx->ivbuf; } - else { - out = ctx->out + (ctx->osize - ctx->remaining); + + if (!ctx->block) { + rv = apr_crypto_block_decrypt_init(&ctx->block, &blockSize, + ctx->iv, ctx->key, f->r->pool); + if (APR_SUCCESS != rv) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, f->r, + APLOGNO(03423) "could not initialise decryption"); + return rv; + } } + } + + if (!finish && !size) { + return APR_SUCCESS; + } + + /* output goes after what is already buffered. Drivers that take the + * passed length as the room available get the real figure. */ + out = ctx->out + ctx->written; + written = ctx->osize + ctx->cipher->blocksize - ctx->written; + + if (ctx->encrypt) { if (!finish) { rv = apr_crypto_block_encrypt(&out, &written, in, size, ctx->block); @@ -649,7 +703,6 @@ do_crypto(ap_filter_t * f, unsigned char *in, apr_off_t size, int finish) return rv; } } - else { rv = apr_crypto_block_encrypt_finish(out, &written, ctx->block); if (APR_SUCCESS != rv) { @@ -659,47 +712,7 @@ do_crypto(ap_filter_t * f, unsigned char *in, apr_off_t size, int finish) } } } - - /* decrypt the given buffer */ else { - - if (!ctx->out) { - out = ctx->out = apr_palloc(f->r->pool, - ctx->osize + ctx->cipher->blocksize); - apr_crypto_clear(f->r->pool, ctx->out, - ctx->osize + ctx->cipher->blocksize); - } - else { - out = ctx->out + (ctx->osize - ctx->remaining); - } - - /* no precomputed iv? assume the first block in the stream is the iv */ - if (need_iv) { - apr_off_t isize = - ctx->cipher->blocksize - (ctx->osize - ctx->remaining); - if (size < isize) { - memcpy(out, in, size); - ctx->remaining -= size; - return APR_SUCCESS; - } - else { - memcpy(out, in, isize); - ctx->remaining -= isize; - out += isize; - ctx->iv = ctx->out; - } - } - - if (!ctx->block) { - rv = apr_crypto_block_decrypt_init(&ctx->block, &blockSize, - ctx->iv, ctx->key, f->r->pool); - if (APR_SUCCESS != rv) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, f->r, - APLOGNO(03423) "could not initialise decryption"); - return rv; - } - } - if (!finish) { rv = apr_crypto_block_decrypt(&out, &written, in, size, ctx->block); @@ -719,9 +732,23 @@ do_crypto(ap_filter_t * f, unsigned char *in, apr_off_t size, int finish) } } - ctx->remaining -= written; + ctx->remaining -= size; ctx->written += written; - ctx->written += extra; + + return APR_SUCCESS; +} + +/** + * Hand the output buffered in ctx->out to ctx->bb, and start a new round. + */ +static apr_status_t crypto_flush(crypto_ctx *ctx) +{ + apr_status_t rv; + + rv = apr_brigade_write(ctx->bb, NULL, NULL, (const char *) ctx->out, + ctx->written); + ctx->remaining = ctx->osize; + ctx->written = 0; return rv; } @@ -732,7 +759,7 @@ do_crypto(ap_filter_t * f, unsigned char *in, apr_off_t size, int finish) static apr_status_t crypto_out_filter(ap_filter_t * f, apr_bucket_brigade * bb) { - apr_bucket *e, *after; + apr_bucket *e; crypto_ctx *ctx = f->ctx; apr_status_t rv = APR_SUCCESS; @@ -747,11 +774,6 @@ crypto_out_filter(ap_filter_t * f, apr_bucket_brigade * bb) apr_table_unset(f->r->headers_out, "Content-Length"); } - /* make sure we fit in the buffer snugly */ - if (APR_BRIGADE_EMPTY(ctx->bb)) { - apr_brigade_partition(bb, ctx->remaining, &after); - } - while (APR_SUCCESS == rv && !APR_BRIGADE_EMPTY(bb)) { const char *data; apr_size_t size; @@ -762,12 +784,14 @@ crypto_out_filter(ap_filter_t * f, apr_bucket_brigade * bb) if (APR_BUCKET_IS_EOS(e)) { /* handle any leftovers */ - do_crypto(f, NULL, 0, 1); - apr_brigade_write(ctx->bb, NULL, NULL, (const char *) ctx->out, - ctx->conf->size - ctx->remaining); - ctx->remaining = ctx->osize; - ctx->written = 0; - apr_brigade_partition(bb, ctx->remaining, &after); + rv = do_crypto(f, NULL, 0, 1); + if (APR_SUCCESS != rv) { + return rv; + } + rv = crypto_flush(ctx); + if (APR_SUCCESS != rv) { + return rv; + } /* pass the EOS across */ APR_BUCKET_REMOVE(e); @@ -812,16 +836,24 @@ crypto_out_filter(ap_filter_t * f, apr_bucket_brigade * bb) if (APR_SUCCESS == (rv = apr_bucket_read(e, &data, &size, APR_BLOCK_READ))) { - do_crypto(f, (unsigned char *) data, size, 0); + /* never feed more than is left in this round */ + if ((apr_off_t) size > ctx->remaining) { + apr_bucket_split(e, (apr_size_t) ctx->remaining); + size = (apr_size_t) ctx->remaining; + } + + rv = do_crypto(f, (unsigned char *) data, size, 0); + if (APR_SUCCESS != rv) { + return rv; + } apr_bucket_delete(e); + /* round complete, pass what we have down the chain */ if (!ctx->remaining) { - apr_brigade_write(ctx->bb, NULL, NULL, - (const char *) ctx->out, ctx->written); - ctx->remaining = ctx->osize; - ctx->written = 0; - apr_brigade_partition(bb, ctx->remaining, &after); - rv = ap_pass_brigade(f->next, ctx->bb); + rv = crypto_flush(ctx); + if (APR_SUCCESS == rv) { + rv = ap_pass_brigade(f->next, ctx->bb); + } } } @@ -855,10 +887,9 @@ crypto_in_filter(ap_filter_t * f, apr_bucket_brigade * bb, /* if our buffer is empty, read off the network until the buffer is full */ if (APR_BRIGADE_EMPTY(ctx->bb)) { - ctx->remaining = ctx->osize; - ctx->written = 0; + int full = 0; - while (!ctx->seen_eos && ctx->remaining > 0) { + while (!ctx->seen_eos && !full) { const char *data; apr_size_t size = 0; @@ -869,8 +900,8 @@ crypto_in_filter(ap_filter_t * f, apr_bucket_brigade * bb, /* if an error was received, bail out now. If the error is * EAGAIN and we have not yet seen an EOS, we will definitely - * be called again, at which point we will send our buffered - * data. Instead of sending EAGAIN, some filters return an + * be called again, at which point we will carry on filling + * our buffer. Instead of sending EAGAIN, some filters return an * empty brigade instead when data is not yet available. In * this case, we drop through and pass buffered data, if any. */ @@ -894,9 +925,14 @@ crypto_in_filter(ap_filter_t * f, apr_bucket_brigade * bb, if (APR_BUCKET_IS_EOS(e)) { /* handle any leftovers */ - do_crypto(f, NULL, 0, 1); - apr_brigade_write(ctx->bb, NULL, NULL, - (const char *) ctx->out, ctx->written); + rv = do_crypto(f, NULL, 0, 1); + if (APR_SUCCESS != rv) { + return rv; + } + rv = crypto_flush(ctx); + if (APR_SUCCESS != rv) { + return rv; + } APR_BUCKET_REMOVE(e); APR_BRIGADE_INSERT_TAIL(ctx->bb, e); @@ -930,14 +966,29 @@ crypto_in_filter(ap_filter_t * f, apr_bucket_brigade * bb, return rv; } - do_crypto(f, (unsigned char *) data, size, 0); - if (!ctx->remaining || APR_STATUS_IS_EAGAIN(rv)) { - apr_brigade_write(ctx->bb, NULL, NULL, - (const char *) ctx->out, ctx->written); + /* never feed more than is left in this round */ + if ((apr_off_t) size > ctx->remaining) { + apr_bucket_split(e, (apr_size_t) ctx->remaining); + size = (apr_size_t) ctx->remaining; } + rv = do_crypto(f, (unsigned char *) data, size, 0); + if (APR_SUCCESS != rv) { + return rv; + } apr_bucket_delete(e); + /* round complete, hand it over. Anything left in ctx->tmp + * waits for the next round. */ + if (!ctx->remaining) { + rv = crypto_flush(ctx); + if (APR_SUCCESS != rv) { + return rv; + } + full = 1; + break; + } + } } } diff --git a/test/modules/filters/env.py b/test/modules/filters/env.py index 16c6d8312f4..256e62b132c 100644 --- a/test/modules/filters/env.py +++ b/test/modules/filters/env.py @@ -16,7 +16,8 @@ def __init__(self, env: 'HttpdTestEnv'): self.add_source_dir(os.path.dirname(inspect.getfile(FiltersTestSetup))) self.add_modules(["substitute", "sed", "buffer", "ext_filter", "include"]) self.add_cgi_module() - self.add_optional_modules(["xml2enc", "proxy_html", "brotli", "deflate"]) + self.add_optional_modules(["xml2enc", "proxy_html", "brotli", "deflate", + "crypto"]) class FiltersTestEnv(HttpdTestEnv): diff --git a/test/modules/filters/htdocs/cgi/echo.py b/test/modules/filters/htdocs/cgi/echo.py new file mode 100755 index 00000000000..3247ea3049b --- /dev/null +++ b/test/modules/filters/htdocs/cgi/echo.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import sys + +# echo the request body back, byte for byte +data = sys.stdin.buffer.read() +sys.stdout.buffer.write(b"Content-Type: application/octet-stream\r\n") +sys.stdout.buffer.write(b"\r\n") +sys.stdout.buffer.write(data) +sys.stdout.buffer.flush() diff --git a/test/modules/filters/test_005_crypto.py b/test/modules/filters/test_005_crypto.py new file mode 100644 index 00000000000..e3e74822566 --- /dev/null +++ b/test/modules/filters/test_005_crypto.py @@ -0,0 +1,189 @@ +import glob +import os +import re +import subprocess + +import pytest +from cryptography.hazmat.primitives import padding +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + +from pyhttpd.conf import HttpdConf +from pyhttpd.depends import needs_dependency +from .env import FiltersTestEnv + +# mod_crypto's ENCRYPT and DECRYPT filters, in both filter stacks, with and +# without a configured CryptoIV, for bodies below, at and above CryptoSize. +# The filters work in rounds of CryptoSize input bytes, so sizes around the +# round boundary are the interesting ones. + +KEY = bytes(range(32)) +IV = bytes(range(100, 116)) +SIZE = 4096 +SIZES = [0, 1, 15, 16, 17, SIZE - 1, SIZE, SIZE + 1, SIZE + 16, 3 * SIZE, + 3 * SIZE + 1, 100000] + + +def plain(size): + return bytes((i * 7 + size) & 0xff for i in range(size)) + + +def encrypt(iv, data): + padder = padding.PKCS7(128).padder() + enc = Cipher(algorithms.AES(KEY), modes.CBC(iv)).encryptor() + return enc.update(padder.update(data) + padder.finalize()) + enc.finalize() + + +def decrypt(iv, data): + unpadder = padding.PKCS7(128).unpadder() + dec = Cipher(algorithms.AES(KEY), modes.CBC(iv)).decryptor() + return unpadder.update(dec.update(data) + dec.finalize()) + unpadder.finalize() + + +def crypto_driver(env): + """The name of an apr crypto driver this apr-util has, or None. + Naming a driver that cannot be loaded keeps httpd from starting.""" + # APU_CONFIG is the apu-1-config of a separate apr-util 1.x, which + # need not sit in APR's bindir, and is empty under APR 2.x, where + # apr-util is merged in and the drivers live under apr-2 instead. + for var, subdir in [("APU_CONFIG", "apr-util-1"), + ("APR_CONFIG", "apr-2")]: + config = env.get_apxs_var(var) + if not config or not os.path.isfile(config): + continue + p = subprocess.run([config, "--link-ld"], capture_output=True, text=True) + m = re.search(r'-L(\S+)', p.stdout) + if not m: + continue + pattern = os.path.join(m.group(1), subdir, "apr_crypto_*.so") + for so in sorted(glob.glob(pattern)): + m = re.match(r'apr_crypto_(\w+?)(-\d+)?\.so$', os.path.basename(so)) + if m: + return m.group(1) + return None + + +@needs_dependency("mod_crypto", FiltersTestEnv.has_shared_module("crypto"), + reason="mod_crypto not available") +class TestCrypto: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env): + driver = crypto_driver(env) + env.require(driver is not None, "no apr crypto driver available", + dep="apr_crypto") + docs = os.path.join(env.server_dir, "htdocs", "crypto") + for sub in ["plain", "enc-iv", "enc-noiv"]: + os.makedirs(os.path.join(docs, sub), exist_ok=True) + key_file = os.path.join(env.gen_dir, "crypto.key") + iv_file = os.path.join(env.gen_dir, "crypto.iv") + for fname, content in [(key_file, KEY), (iv_file, IV)]: + with open(fname, "wb") as fd: + fd.write(content) + for size in SIZES: + data = plain(size) + iv = os.urandom(16) + for sub, content in [("plain", data), + ("enc-iv", encrypt(IV, data)), + ("enc-noiv", iv + encrypt(iv, data))]: + with open(os.path.join(docs, sub, str(size)), "wb") as fd: + fd.write(content) + + def location(path, filter_dir, flt, with_iv): + return [ + f"", + f" Set{filter_dir}Filter {flt}", + f" CryptoSize {SIZE}", + " CryptoCipher aes256 cbc", + f" CryptoKey file:{key_file}", + f" CryptoIV file:{iv_file}" if with_iv else " CryptoIV none", + "", + ] + + conf = HttpdConf(env) + conf.add(f"CryptoDriver {driver}") + conf.start_vhost(domains=[f"crypto.{env.http_tld}"], + port=env.http_port, doc_root="htdocs/crypto") + conf.add([ + f"Alias /enc-iv {docs}/plain", + f"Alias /enc-noiv {docs}/plain", + f"Alias /dec-iv {docs}/enc-iv", + f"Alias /dec-noiv {docs}/enc-noiv", + ]) + conf.add(location("/enc-iv", "Output", "ENCRYPT", True)) + conf.add(location("/enc-noiv", "Output", "ENCRYPT", False)) + conf.add(location("/dec-iv", "Output", "DECRYPT", True)) + conf.add(location("/dec-noiv", "Output", "DECRYPT", False)) + for path in ["/in-enc-iv", "/in-enc-noiv", "/in-dec-iv", "/in-dec-noiv"]: + conf.add(f"Alias {path} {env.server_dir}/htdocs/cgi") + conf.add(location("/in-enc-iv", "Input", "ENCRYPT", True)) + conf.add(location("/in-enc-noiv", "Input", "ENCRYPT", False)) + conf.add(location("/in-dec-iv", "Input", "DECRYPT", True)) + conf.add(location("/in-dec-noiv", "Input", "DECRYPT", False)) + conf.end_vhost() + conf.install() + assert env.apache_restart() == 0 + + def get(self, env, path): + r = env.curl_get(env.mkurl("http", "crypto", path)) + assert r.exit_code == 0, r + assert r.response["status"] == 200, r + return r.response["body"] + + def post(self, env, path, data): + fpath = os.path.join(env.gen_dir, "crypto-body") + with open(fpath, "wb") as fd: + fd.write(data) + r = env.curl_get(env.mkurl("http", "crypto", f"{path}/echo.py"), + options=["--data-binary", f"@{fpath}", + "-H", "Content-Type: application/octet-stream"]) + assert r.exit_code == 0, r + assert r.response["status"] == 200, r + return r.response["body"] + + # ENCRYPT output filter, configured iv: the output is the ciphertext + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_01(self, env, size): + assert self.get(env, f"/enc-iv/{size}") == encrypt(IV, plain(size)) + + # ENCRYPT output filter, generated iv: the iv leads the ciphertext + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_02(self, env, size): + body = self.get(env, f"/enc-noiv/{size}") + assert len(body) == 16 + len(encrypt(IV, plain(size))) + assert decrypt(body[:16], body[16:]) == plain(size) + + # DECRYPT output filter, configured iv + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_03(self, env, size): + assert self.get(env, f"/dec-iv/{size}") == plain(size) + + # DECRYPT output filter, iv read from the stream + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_04(self, env, size): + assert self.get(env, f"/dec-noiv/{size}") == plain(size) + + # ENCRYPT input filter, configured iv + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_05(self, env, size): + body = self.post(env, "/in-enc-iv", plain(size)) + assert body == encrypt(IV, plain(size)) + + # ENCRYPT input filter, generated iv + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_06(self, env, size): + body = self.post(env, "/in-enc-noiv", plain(size)) + assert len(body) == 16 + len(encrypt(IV, plain(size))) + assert decrypt(body[:16], body[16:]) == plain(size) + + # DECRYPT input filter, configured iv + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_07(self, env, size): + body = self.post(env, "/in-dec-iv", encrypt(IV, plain(size))) + assert body == plain(size) + + # DECRYPT input filter, iv read from the stream + @pytest.mark.parametrize("size", SIZES) + def test_filters_005_08(self, env, size): + iv = os.urandom(16) + body = self.post(env, "/in-dec-noiv", iv + encrypt(iv, plain(size))) + assert body == plain(size)